diff --git a/VQA_model/DOVER/.eggs/README.txt b/VQA_model/DOVER/.eggs/README.txt
new file mode 100644
index 0000000000000000000000000000000000000000..5d01668824f45c3a6683e12d1b9048bb1d273041
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/README.txt
@@ -0,0 +1,6 @@
+This directory contains eggs that were downloaded by setuptools to build, test, and run plug-ins.
+
+This directory caches those eggs to prevent repeated downloads.
+
+However, it is safe to delete this directory.
+
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/LICENSE.txt b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..7d18210bc55ab19347d7f8781222b89e5cda9c11
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/LICENSE.txt
@@ -0,0 +1,910 @@
+Copyright (c) 2005-2022, 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: .libs/libopenb*.so
+Description: bundled as a dynamically linked library
+Availability: https://github.com/xianyi/OpenBLAS/
+License: 3-clause BSD
+ 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: .libs/libopenb*.so
+Description: bundled in OpenBLAS
+Availability: https://github.com/xianyi/OpenBLAS/
+License 3-clause BSD
+ 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: .libs/libgfortran*.so
+Description: dynamically linked to files compiled with gcc
+Availability: https://gcc.gnu.org/viewcvs/gcc/
+License: GPLv3 + runtime exception
+ 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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__config__.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__config__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2590dbb984e5c2eb2f54a083b805d4fa9b744b42
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__config__.py
@@ -0,0 +1,115 @@
+# This file is generated by numpy's setup.py
+# It contains system_info results at the time of building this package.
+__all__ = ["get_info","show"]
+
+
+import os
+import sys
+
+extra_dll_dir = os.path.join(os.path.dirname(__file__), '.libs')
+
+if sys.platform == 'win32' and os.path.isdir(extra_dll_dir):
+ os.add_dll_directory(extra_dll_dir)
+
+openblas64__info={'libraries': ['openblas64_', 'openblas64_'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)], 'runtime_library_dirs': ['/usr/local/lib']}
+blas_ilp64_opt_info={'libraries': ['openblas64_', 'openblas64_'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None)], 'runtime_library_dirs': ['/usr/local/lib']}
+openblas64__lapack_info={'libraries': ['openblas64_', 'openblas64_'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)], 'runtime_library_dirs': ['/usr/local/lib']}
+lapack_ilp64_opt_info={'libraries': ['openblas64_', 'openblas64_'], 'library_dirs': ['/usr/local/lib'], 'language': 'c', 'define_macros': [('HAVE_CBLAS', None), ('BLAS_SYMBOL_SUFFIX', '64_'), ('HAVE_BLAS_ILP64', None), ('HAVE_LAPACKE', None)], 'runtime_library_dirs': ['/usr/local/lib']}
+
+def get_info(name):
+ g = globals()
+ return g.get(name, g.get(name + "_info", {}))
+
+def show():
+ """
+ Show libraries in the system on which NumPy was built.
+
+ Print information about various resources (libraries, library
+ directories, include directories, etc.) in the system on which
+ NumPy was built.
+
+ See Also
+ --------
+ get_include : Returns the directory containing NumPy C
+ header files.
+
+ Notes
+ -----
+ 1. Classes specifying the information to be printed are defined
+ in the `numpy.distutils.system_info` module.
+
+ Information may include:
+
+ * ``language``: language used to write the libraries (mostly
+ C or f77)
+ * ``libraries``: names of libraries found in the system
+ * ``library_dirs``: directories containing the libraries
+ * ``include_dirs``: directories containing library header files
+ * ``src_dirs``: directories containing library source files
+ * ``define_macros``: preprocessor macros used by
+ ``distutils.setup``
+ * ``baseline``: minimum CPU features required
+ * ``found``: dispatched features supported in the system
+ * ``not found``: dispatched features that are not supported
+ in the system
+
+ 2. NumPy BLAS/LAPACK Installation Notes
+
+ Installing a numpy wheel (``pip install numpy`` or force it
+ via ``pip install numpy --only-binary :numpy: numpy``) includes
+ an OpenBLAS implementation of the BLAS and LAPACK linear algebra
+ APIs. In this case, ``library_dirs`` reports the original build
+ time configuration as compiled with gcc/gfortran; at run time
+ the OpenBLAS library is in
+ ``site-packages/numpy.libs/`` (linux), or
+ ``site-packages/numpy/.dylibs/`` (macOS), or
+ ``site-packages/numpy/.libs/`` (windows).
+
+ Installing numpy from source
+ (``pip install numpy --no-binary numpy``) searches for BLAS and
+ LAPACK dynamic link libraries at build time as influenced by
+ environment variables NPY_BLAS_LIBS, NPY_CBLAS_LIBS, and
+ NPY_LAPACK_LIBS; or NPY_BLAS_ORDER and NPY_LAPACK_ORDER;
+ or the optional file ``~/.numpy-site.cfg``.
+ NumPy remembers those locations and expects to load the same
+ libraries at run-time.
+ In NumPy 1.21+ on macOS, 'accelerate' (Apple's Accelerate BLAS
+ library) is in the default build-time search order after
+ 'openblas'.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> np.show_config()
+ blas_opt_info:
+ language = c
+ define_macros = [('HAVE_CBLAS', None)]
+ libraries = ['openblas', 'openblas']
+ library_dirs = ['/usr/local/lib']
+ """
+ from numpy.core._multiarray_umath import (
+ __cpu_features__, __cpu_baseline__, __cpu_dispatch__
+ )
+ for name,info_dict in globals().items():
+ if name[0] == "_" or type(info_dict) is not type({}): continue
+ print(name + ":")
+ if not info_dict:
+ print(" NOT AVAILABLE")
+ for k,v in info_dict.items():
+ v = str(v)
+ if k == "sources" and len(v) > 200:
+ v = v[:60] + " ...\n... " + v[-60:]
+ print(" %s = %s" % (k,v))
+
+ features_found, features_not_found = [], []
+ for feature in __cpu_dispatch__:
+ if __cpu_features__[feature]:
+ features_found.append(feature)
+ else:
+ features_not_found.append(feature)
+
+ print("Supported SIMD extensions in this NumPy install:")
+ print(" baseline = %s" % (','.join(__cpu_baseline__)))
+ print(" found = %s" % (','.join(features_found)))
+ print(" not found = %s" % (','.join(features_not_found)))
+
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.cython-30.pxd b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.cython-30.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..5fd6086e0701d9fa400333dcc4088152e1ccd86d
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.cython-30.pxd
@@ -0,0 +1,1052 @@
+# NumPy static imports for Cython >= 3.0
+#
+# If any of the PyArray_* functions are called, import_array must be
+# called first. This is done automatically by Cython 3.0+ if a call
+# is not detected inside of the module.
+#
+# Author: Dag Sverre Seljebotn
+#
+
+from cpython.ref cimport Py_INCREF
+from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck
+cimport libc.stdio as stdio
+
+
+cdef extern from *:
+ # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython.
+ # See https://github.com/cython/cython/issues/3573
+ """
+ /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */
+ """
+
+
+cdef extern from "Python.h":
+ ctypedef Py_ssize_t Py_intptr_t
+
+cdef extern from "numpy/arrayobject.h":
+ ctypedef Py_intptr_t npy_intp
+ ctypedef size_t npy_uintp
+
+ cdef enum NPY_TYPES:
+ NPY_BOOL
+ NPY_BYTE
+ NPY_UBYTE
+ NPY_SHORT
+ NPY_USHORT
+ NPY_INT
+ NPY_UINT
+ NPY_LONG
+ NPY_ULONG
+ NPY_LONGLONG
+ NPY_ULONGLONG
+ NPY_FLOAT
+ NPY_DOUBLE
+ NPY_LONGDOUBLE
+ NPY_CFLOAT
+ NPY_CDOUBLE
+ NPY_CLONGDOUBLE
+ NPY_OBJECT
+ NPY_STRING
+ NPY_UNICODE
+ NPY_VOID
+ NPY_DATETIME
+ NPY_TIMEDELTA
+ NPY_NTYPES
+ NPY_NOTYPE
+
+ NPY_INT8
+ NPY_INT16
+ NPY_INT32
+ NPY_INT64
+ NPY_INT128
+ NPY_INT256
+ NPY_UINT8
+ NPY_UINT16
+ NPY_UINT32
+ NPY_UINT64
+ NPY_UINT128
+ NPY_UINT256
+ NPY_FLOAT16
+ NPY_FLOAT32
+ NPY_FLOAT64
+ NPY_FLOAT80
+ NPY_FLOAT96
+ NPY_FLOAT128
+ NPY_FLOAT256
+ NPY_COMPLEX32
+ NPY_COMPLEX64
+ NPY_COMPLEX128
+ NPY_COMPLEX160
+ NPY_COMPLEX192
+ NPY_COMPLEX256
+ NPY_COMPLEX512
+
+ NPY_INTP
+
+ ctypedef enum NPY_ORDER:
+ NPY_ANYORDER
+ NPY_CORDER
+ NPY_FORTRANORDER
+ NPY_KEEPORDER
+
+ ctypedef enum NPY_CASTING:
+ NPY_NO_CASTING
+ NPY_EQUIV_CASTING
+ NPY_SAFE_CASTING
+ NPY_SAME_KIND_CASTING
+ NPY_UNSAFE_CASTING
+
+ ctypedef enum NPY_CLIPMODE:
+ NPY_CLIP
+ NPY_WRAP
+ NPY_RAISE
+
+ ctypedef enum NPY_SCALARKIND:
+ NPY_NOSCALAR,
+ NPY_BOOL_SCALAR,
+ NPY_INTPOS_SCALAR,
+ NPY_INTNEG_SCALAR,
+ NPY_FLOAT_SCALAR,
+ NPY_COMPLEX_SCALAR,
+ NPY_OBJECT_SCALAR
+
+ ctypedef enum NPY_SORTKIND:
+ NPY_QUICKSORT
+ NPY_HEAPSORT
+ NPY_MERGESORT
+
+ ctypedef enum NPY_SEARCHSIDE:
+ NPY_SEARCHLEFT
+ NPY_SEARCHRIGHT
+
+ enum:
+ # DEPRECATED since NumPy 1.7 ! Do not use in new code!
+ NPY_C_CONTIGUOUS
+ NPY_F_CONTIGUOUS
+ NPY_CONTIGUOUS
+ NPY_FORTRAN
+ NPY_OWNDATA
+ NPY_FORCECAST
+ NPY_ENSURECOPY
+ NPY_ENSUREARRAY
+ NPY_ELEMENTSTRIDES
+ NPY_ALIGNED
+ NPY_NOTSWAPPED
+ NPY_WRITEABLE
+ NPY_ARR_HAS_DESCR
+
+ NPY_BEHAVED
+ NPY_BEHAVED_NS
+ NPY_CARRAY
+ NPY_CARRAY_RO
+ NPY_FARRAY
+ NPY_FARRAY_RO
+ NPY_DEFAULT
+
+ NPY_IN_ARRAY
+ NPY_OUT_ARRAY
+ NPY_INOUT_ARRAY
+ NPY_IN_FARRAY
+ NPY_OUT_FARRAY
+ NPY_INOUT_FARRAY
+
+ NPY_UPDATE_ALL
+
+ enum:
+ # Added in NumPy 1.7 to replace the deprecated enums above.
+ NPY_ARRAY_C_CONTIGUOUS
+ NPY_ARRAY_F_CONTIGUOUS
+ NPY_ARRAY_OWNDATA
+ NPY_ARRAY_FORCECAST
+ NPY_ARRAY_ENSURECOPY
+ NPY_ARRAY_ENSUREARRAY
+ NPY_ARRAY_ELEMENTSTRIDES
+ NPY_ARRAY_ALIGNED
+ NPY_ARRAY_NOTSWAPPED
+ NPY_ARRAY_WRITEABLE
+ NPY_ARRAY_WRITEBACKIFCOPY
+
+ NPY_ARRAY_BEHAVED
+ NPY_ARRAY_BEHAVED_NS
+ NPY_ARRAY_CARRAY
+ NPY_ARRAY_CARRAY_RO
+ NPY_ARRAY_FARRAY
+ NPY_ARRAY_FARRAY_RO
+ NPY_ARRAY_DEFAULT
+
+ NPY_ARRAY_IN_ARRAY
+ NPY_ARRAY_OUT_ARRAY
+ NPY_ARRAY_INOUT_ARRAY
+ NPY_ARRAY_IN_FARRAY
+ NPY_ARRAY_OUT_FARRAY
+ NPY_ARRAY_INOUT_FARRAY
+
+ NPY_ARRAY_UPDATE_ALL
+
+ cdef enum:
+ NPY_MAXDIMS
+
+ npy_intp NPY_MAX_ELSIZE
+
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
+
+ ctypedef struct PyArray_ArrayDescr:
+ # shape is a tuple, but Cython doesn't support "tuple shape"
+ # inside a non-PyObject declaration, so we have to declare it
+ # as just a PyObject*.
+ PyObject* shape
+
+ ctypedef struct PyArray_Descr:
+ pass
+
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
+ # Use PyDataType_* macros when possible, however there are no macros
+ # for accessing some of the fields, so some are defined.
+ cdef PyTypeObject* typeobj
+ cdef char kind
+ cdef char type
+ # Numpy sometimes mutates this without warning (e.g. it'll
+ # sometimes change "|" to "<" in shared dtype objects on
+ # little-endian machines). If this matters to you, use
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
+ # directly accessing this field.
+ cdef char byteorder
+ cdef char flags
+ cdef int type_num
+ cdef int itemsize "elsize"
+ cdef int alignment
+ cdef object fields
+ cdef tuple names
+ # Use PyDataType_HASSUBARRAY to test whether this field is
+ # valid (the pointer can be NULL). Most users should access
+ # this field via the inline helper method PyDataType_SHAPE.
+ cdef PyArray_ArrayDescr* subarray
+
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
+ # Use through macros
+ pass
+
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
+ # Use through macros
+ pass
+
+ ctypedef struct PyArrayObject:
+ # For use in situations where ndarray can't replace PyArrayObject*,
+ # like PyArrayObject**.
+ pass
+
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
+
+ # NOTE: no field declarations since direct access is deprecated since NumPy 1.7
+ # Instead, we use properties that map to the corresponding C-API functions.
+
+ @property
+ cdef inline PyObject* base(self) nogil:
+ """Returns a borrowed reference to the object owning the data/memory.
+ """
+ return PyArray_BASE(self)
+
+ @property
+ cdef inline dtype descr(self):
+ """Returns an owned reference to the dtype of the array.
+ """
+ return PyArray_DESCR(self)
+
+ @property
+ cdef inline int ndim(self) nogil:
+ """Returns the number of dimensions in the array.
+ """
+ return PyArray_NDIM(self)
+
+ @property
+ cdef inline npy_intp *shape(self) nogil:
+ """Returns a pointer to the dimensions/shape of the array.
+ The number of elements matches the number of dimensions of the array (ndim).
+ Can return NULL for 0-dimensional arrays.
+ """
+ return PyArray_DIMS(self)
+
+ @property
+ cdef inline npy_intp *strides(self) nogil:
+ """Returns a pointer to the strides of the array.
+ The number of elements matches the number of dimensions of the array (ndim).
+ """
+ return PyArray_STRIDES(self)
+
+ @property
+ cdef inline npy_intp size(self) nogil:
+ """Returns the total size (in number of elements) of the array.
+ """
+ return PyArray_SIZE(self)
+
+ @property
+ cdef inline char* data(self) nogil:
+ """The pointer to the data buffer as a char*.
+ This is provided for legacy reasons to avoid direct struct field access.
+ For new code that needs this access, you probably want to cast the result
+ of `PyArray_DATA()` instead, which returns a 'void*'.
+ """
+ return PyArray_BYTES(self)
+
+ ctypedef unsigned char npy_bool
+
+ ctypedef signed char npy_byte
+ ctypedef signed short npy_short
+ ctypedef signed int npy_int
+ ctypedef signed long npy_long
+ ctypedef signed long long npy_longlong
+
+ ctypedef unsigned char npy_ubyte
+ ctypedef unsigned short npy_ushort
+ ctypedef unsigned int npy_uint
+ ctypedef unsigned long npy_ulong
+ ctypedef unsigned long long npy_ulonglong
+
+ ctypedef float npy_float
+ ctypedef double npy_double
+ ctypedef long double npy_longdouble
+
+ ctypedef signed char npy_int8
+ ctypedef signed short npy_int16
+ ctypedef signed int npy_int32
+ ctypedef signed long long npy_int64
+ ctypedef signed long long npy_int96
+ ctypedef signed long long npy_int128
+
+ ctypedef unsigned char npy_uint8
+ ctypedef unsigned short npy_uint16
+ ctypedef unsigned int npy_uint32
+ ctypedef unsigned long long npy_uint64
+ ctypedef unsigned long long npy_uint96
+ ctypedef unsigned long long npy_uint128
+
+ ctypedef float npy_float32
+ ctypedef double npy_float64
+ ctypedef long double npy_float80
+ ctypedef long double npy_float96
+ ctypedef long double npy_float128
+
+ ctypedef struct npy_cfloat:
+ float real
+ float imag
+
+ ctypedef struct npy_cdouble:
+ double real
+ double imag
+
+ ctypedef struct npy_clongdouble:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex64:
+ float real
+ float imag
+
+ ctypedef struct npy_complex128:
+ double real
+ double imag
+
+ ctypedef struct npy_complex160:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex192:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex256:
+ long double real
+ long double imag
+
+ ctypedef struct PyArray_Dims:
+ npy_intp *ptr
+ int len
+
+ int _import_array() except -1
+ # A second definition so _import_array isn't marked as used when we use it here.
+ # Do not use - subject to change any time.
+ int __pyx_import_array "_import_array"() except -1
+
+ #
+ # Macros from ndarrayobject.h
+ #
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
+ bint PyArray_ISALIGNED(ndarray m) nogil
+
+ int PyArray_NDIM(ndarray) nogil
+ bint PyArray_ISONESEGMENT(ndarray) nogil
+ bint PyArray_ISFORTRAN(ndarray) nogil
+ int PyArray_FORTRANIF(ndarray) nogil
+
+ void* PyArray_DATA(ndarray) nogil
+ char* PyArray_BYTES(ndarray) nogil
+
+ npy_intp* PyArray_DIMS(ndarray) nogil
+ npy_intp* PyArray_STRIDES(ndarray) nogil
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
+
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
+ PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr.
+ int PyArray_FLAGS(ndarray) nogil
+ void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
+ void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
+ int PyArray_TYPE(ndarray arr) nogil
+
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj)
+
+ bint PyTypeNum_ISBOOL(int) nogil
+ bint PyTypeNum_ISUNSIGNED(int) nogil
+ bint PyTypeNum_ISSIGNED(int) nogil
+ bint PyTypeNum_ISINTEGER(int) nogil
+ bint PyTypeNum_ISFLOAT(int) nogil
+ bint PyTypeNum_ISNUMBER(int) nogil
+ bint PyTypeNum_ISSTRING(int) nogil
+ bint PyTypeNum_ISCOMPLEX(int) nogil
+ bint PyTypeNum_ISPYTHON(int) nogil
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
+ bint PyTypeNum_ISUSERDEF(int) nogil
+ bint PyTypeNum_ISEXTENDED(int) nogil
+ bint PyTypeNum_ISOBJECT(int) nogil
+
+ bint PyDataType_ISBOOL(dtype) nogil
+ bint PyDataType_ISUNSIGNED(dtype) nogil
+ bint PyDataType_ISSIGNED(dtype) nogil
+ bint PyDataType_ISINTEGER(dtype) nogil
+ bint PyDataType_ISFLOAT(dtype) nogil
+ bint PyDataType_ISNUMBER(dtype) nogil
+ bint PyDataType_ISSTRING(dtype) nogil
+ bint PyDataType_ISCOMPLEX(dtype) nogil
+ bint PyDataType_ISPYTHON(dtype) nogil
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
+ bint PyDataType_ISUSERDEF(dtype) nogil
+ bint PyDataType_ISEXTENDED(dtype) nogil
+ bint PyDataType_ISOBJECT(dtype) nogil
+ bint PyDataType_HASFIELDS(dtype) nogil
+ bint PyDataType_HASSUBARRAY(dtype) nogil
+
+ bint PyArray_ISBOOL(ndarray) nogil
+ bint PyArray_ISUNSIGNED(ndarray) nogil
+ bint PyArray_ISSIGNED(ndarray) nogil
+ bint PyArray_ISINTEGER(ndarray) nogil
+ bint PyArray_ISFLOAT(ndarray) nogil
+ bint PyArray_ISNUMBER(ndarray) nogil
+ bint PyArray_ISSTRING(ndarray) nogil
+ bint PyArray_ISCOMPLEX(ndarray) nogil
+ bint PyArray_ISPYTHON(ndarray) nogil
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
+ bint PyArray_ISUSERDEF(ndarray) nogil
+ bint PyArray_ISEXTENDED(ndarray) nogil
+ bint PyArray_ISOBJECT(ndarray) nogil
+ bint PyArray_HASFIELDS(ndarray) nogil
+
+ bint PyArray_ISVARIABLE(ndarray) nogil
+
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
+
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
+
+ bint PyArray_ISCARRAY(ndarray) nogil
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
+ bint PyArray_ISFARRAY(ndarray) nogil
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
+ bint PyArray_ISBEHAVED(ndarray) nogil
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
+
+
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
+
+ bint PyArray_DescrCheck(object)
+
+ bint PyArray_Check(object)
+ bint PyArray_CheckExact(object)
+
+ # Cannot be supported due to out arg:
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
+ # bint PyArray_HasArrayInterface(op, out)
+
+
+ bint PyArray_IsZeroDim(object)
+ # Cannot be supported due to ## ## in macro:
+ # bint PyArray_IsScalar(object, verbatim work)
+ bint PyArray_CheckScalar(object)
+ bint PyArray_IsPythonNumber(object)
+ bint PyArray_IsPythonScalar(object)
+ bint PyArray_IsAnyScalar(object)
+ bint PyArray_CheckAnyScalar(object)
+
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
+ npy_intp PyArray_SIZE(ndarray) nogil
+ npy_intp PyArray_NBYTES(ndarray) nogil
+
+ object PyArray_FROM_O(object)
+ object PyArray_FROM_OF(object m, int flags)
+ object PyArray_FROM_OT(object m, int type)
+ object PyArray_FROM_OTF(object m, int type, int flags)
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
+ void PyArray_FILLWBYTE(object, int val)
+ npy_intp PyArray_REFCOUNT(object)
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
+ object PyArray_ToScalar(void* data, ndarray arr)
+
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
+
+ void PyArray_XDECREF_ERR(ndarray)
+ # Cannot be supported due to out arg
+ # void PyArray_DESCR_REPLACE(descr)
+
+
+ object PyArray_Copy(ndarray)
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
+
+ object PyArray_Cast(ndarray mp, int type_num)
+ object PyArray_Take(ndarray ap, object items, int axis)
+ object PyArray_Put(ndarray ap, object items, object values)
+
+ void PyArray_ITER_RESET(flatiter it) nogil
+ void PyArray_ITER_NEXT(flatiter it) nogil
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
+ void* PyArray_ITER_DATA(flatiter it) nogil
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
+
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
+
+ # Functions from __multiarray_api.h
+
+ # Functions taking dtype and returning object/ndarray are disabled
+ # for now as they steal dtype references. I'm conservative and disable
+ # more than is probably needed until it can be checked further.
+ int PyArray_SetNumericOps (object)
+ object PyArray_GetNumericOps ()
+ int PyArray_INCREF (ndarray)
+ int PyArray_XDECREF (ndarray)
+ void PyArray_SetStringFunction (object, int)
+ dtype PyArray_DescrFromType (int)
+ object PyArray_TypeObjectFromType (int)
+ char * PyArray_Zero (ndarray)
+ char * PyArray_One (ndarray)
+ #object PyArray_CastToType (ndarray, dtype, int)
+ int PyArray_CastTo (ndarray, ndarray)
+ int PyArray_CastAnyTo (ndarray, ndarray)
+ int PyArray_CanCastSafely (int, int)
+ npy_bool PyArray_CanCastTo (dtype, dtype)
+ int PyArray_ObjectType (object, int)
+ dtype PyArray_DescrFromObject (object, dtype)
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
+ dtype PyArray_DescrFromScalar (object)
+ dtype PyArray_DescrFromTypeObject (object)
+ npy_intp PyArray_Size (object)
+ #object PyArray_Scalar (void *, dtype, object)
+ #object PyArray_FromScalar (object, dtype)
+ void PyArray_ScalarAsCtype (object, void *)
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
+ object PyArray_ScalarFromObject (object)
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
+ object PyArray_FromDims (int, int *, int)
+ #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
+ object PyArray_EnsureArray (object)
+ object PyArray_EnsureAnyArray (object)
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
+ #object PyArray_FromIter (object, dtype, npy_intp)
+ object PyArray_Return (ndarray)
+ #object PyArray_GetField (ndarray, dtype, int)
+ #int PyArray_SetField (ndarray, dtype, int, object)
+ object PyArray_Byteswap (ndarray, npy_bool)
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
+ int PyArray_MoveInto (ndarray, ndarray)
+ int PyArray_CopyInto (ndarray, ndarray)
+ int PyArray_CopyAnyInto (ndarray, ndarray)
+ int PyArray_CopyObject (ndarray, object)
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
+ object PyArray_ToList (ndarray)
+ object PyArray_ToString (ndarray, NPY_ORDER)
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *)
+ int PyArray_Dump (object, object, int)
+ object PyArray_Dumps (object, int)
+ int PyArray_ValidType (int)
+ void PyArray_UpdateFlags (ndarray, int)
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
+ #dtype PyArray_DescrNew (dtype)
+ dtype PyArray_DescrNewFromType (int)
+ double PyArray_GetPriority (object, double)
+ object PyArray_IterNew (object)
+ object PyArray_MultiIterNew (int, ...)
+
+ int PyArray_PyIntAsInt (object)
+ npy_intp PyArray_PyIntAsIntp (object)
+ int PyArray_Broadcast (broadcast)
+ void PyArray_FillObjectArray (ndarray, object)
+ int PyArray_FillWithScalar (ndarray, object)
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
+ dtype PyArray_DescrNewByteorder (dtype, char)
+ object PyArray_IterAllButAxis (object, int *)
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
+ #object PyArray_FromArray (ndarray, dtype, int)
+ object PyArray_FromInterface (object)
+ object PyArray_FromStructInterface (object)
+ #object PyArray_FromArrayAttr (object, dtype, object)
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
+ object PyArray_NewFlagsObject (object)
+ npy_bool PyArray_CanCastScalar (type, type)
+ #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
+ int PyArray_RemoveSmallest (broadcast)
+ int PyArray_ElementStrides (object)
+ void PyArray_Item_INCREF (char *, dtype)
+ void PyArray_Item_XDECREF (char *, dtype)
+ object PyArray_FieldNames (object)
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
+ object PyArray_PutMask (ndarray, object, object)
+ object PyArray_Repeat (ndarray, object, int)
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND)
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
+ object PyArray_ArgMax (ndarray, int, ndarray)
+ object PyArray_ArgMin (ndarray, int, ndarray)
+ object PyArray_Reshape (ndarray, object)
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
+ object PyArray_Squeeze (ndarray)
+ #object PyArray_View (ndarray, dtype, type)
+ object PyArray_SwapAxes (ndarray, int, int)
+ object PyArray_Max (ndarray, int, ndarray)
+ object PyArray_Min (ndarray, int, ndarray)
+ object PyArray_Ptp (ndarray, int, ndarray)
+ object PyArray_Mean (ndarray, int, int, ndarray)
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
+ object PyArray_Diagonal (ndarray, int, int, int)
+ object PyArray_Clip (ndarray, object, object, ndarray)
+ object PyArray_Conjugate (ndarray, ndarray)
+ object PyArray_Nonzero (ndarray)
+ object PyArray_Std (ndarray, int, int, ndarray, int)
+ object PyArray_Sum (ndarray, int, int, ndarray)
+ object PyArray_CumSum (ndarray, int, int, ndarray)
+ object PyArray_Prod (ndarray, int, int, ndarray)
+ object PyArray_CumProd (ndarray, int, int, ndarray)
+ object PyArray_All (ndarray, int, ndarray)
+ object PyArray_Any (ndarray, int, ndarray)
+ object PyArray_Compress (ndarray, object, int, ndarray)
+ object PyArray_Flatten (ndarray, NPY_ORDER)
+ object PyArray_Ravel (ndarray, NPY_ORDER)
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
+ int PyArray_MultiplyIntList (int *, int)
+ void * PyArray_GetPtr (ndarray, npy_intp*)
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
+ #int PyArray_As1D (object*, char **, int *, int)
+ #int PyArray_As2D (object*, char ***, int *, int *, int)
+ int PyArray_Free (object, void *)
+ #int PyArray_Converter (object, object*)
+ int PyArray_IntpFromSequence (object, npy_intp *, int)
+ object PyArray_Concatenate (object, int)
+ object PyArray_InnerProduct (object, object)
+ object PyArray_MatrixProduct (object, object)
+ object PyArray_CopyAndTranspose (object)
+ object PyArray_Correlate (object, object, int)
+ int PyArray_TypestrConvert (int, int)
+ #int PyArray_DescrConverter (object, dtype*)
+ #int PyArray_DescrConverter2 (object, dtype*)
+ int PyArray_IntpConverter (object, PyArray_Dims *)
+ #int PyArray_BufferConverter (object, chunk)
+ int PyArray_AxisConverter (object, int *)
+ int PyArray_BoolConverter (object, npy_bool *)
+ int PyArray_ByteorderConverter (object, char *)
+ int PyArray_OrderConverter (object, NPY_ORDER *)
+ unsigned char PyArray_EquivTypes (dtype, dtype)
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
+ object PyArray_Where (object, object, object)
+ object PyArray_Arange (double, double, double, int)
+ #object PyArray_ArangeObj (object, object, object, dtype)
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *)
+ object PyArray_LexSort (object, int)
+ object PyArray_Round (ndarray, int, ndarray)
+ unsigned char PyArray_EquivTypenums (int, int)
+ int PyArray_RegisterDataType (dtype)
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *)
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND)
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
+ int PyArray_TypeNumFromName (char *)
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *)
+ #int PyArray_OutputConverter (object, ndarray*)
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
+ void _PyArray_SigintHandler (int)
+ void* _PyArray_GetSigintBuf ()
+ #int PyArray_DescrAlignConverter (object, dtype*)
+ #int PyArray_DescrAlignConverter2 (object, dtype*)
+ int PyArray_SearchsideConverter (object, void *)
+ object PyArray_CheckAxis (ndarray, int *, int)
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
+ int PyArray_CompareString (char *, char *, size_t)
+ int PyArray_SetBaseObject(ndarray, base) # NOTE: steals a reference to base! Use "set_array_base()" instead.
+
+
+# Typedefs that matches the runtime dtype objects in
+# the numpy module.
+
+# The ones that are commented out needs an IFDEF function
+# in Cython to enable them only on the right systems.
+
+ctypedef npy_int8 int8_t
+ctypedef npy_int16 int16_t
+ctypedef npy_int32 int32_t
+ctypedef npy_int64 int64_t
+#ctypedef npy_int96 int96_t
+#ctypedef npy_int128 int128_t
+
+ctypedef npy_uint8 uint8_t
+ctypedef npy_uint16 uint16_t
+ctypedef npy_uint32 uint32_t
+ctypedef npy_uint64 uint64_t
+#ctypedef npy_uint96 uint96_t
+#ctypedef npy_uint128 uint128_t
+
+ctypedef npy_float32 float32_t
+ctypedef npy_float64 float64_t
+#ctypedef npy_float80 float80_t
+#ctypedef npy_float128 float128_t
+
+ctypedef float complex complex64_t
+ctypedef double complex complex128_t
+
+# The int types are mapped a bit surprising --
+# numpy.int corresponds to 'l' and numpy.long to 'q'
+ctypedef npy_long int_t
+ctypedef npy_longlong long_t
+ctypedef npy_longlong longlong_t
+
+ctypedef npy_ulong uint_t
+ctypedef npy_ulonglong ulong_t
+ctypedef npy_ulonglong ulonglong_t
+
+ctypedef npy_intp intp_t
+ctypedef npy_uintp uintp_t
+
+ctypedef npy_double float_t
+ctypedef npy_double double_t
+ctypedef npy_longdouble longdouble_t
+
+ctypedef npy_cfloat cfloat_t
+ctypedef npy_cdouble cdouble_t
+ctypedef npy_clongdouble clongdouble_t
+
+ctypedef npy_cdouble complex_t
+
+cdef inline object PyArray_MultiIterNew1(a):
+ return PyArray_MultiIterNew(1, a)
+
+cdef inline object PyArray_MultiIterNew2(a, b):
+ return PyArray_MultiIterNew(2, a, b)
+
+cdef inline object PyArray_MultiIterNew3(a, b, c):
+ return PyArray_MultiIterNew(3, a, b, c)
+
+cdef inline object PyArray_MultiIterNew4(a, b, c, d):
+ return PyArray_MultiIterNew(4, a, b, c, d)
+
+cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
+ return PyArray_MultiIterNew(5, a, b, c, d, e)
+
+cdef inline tuple PyDataType_SHAPE(dtype d):
+ if PyDataType_HASSUBARRAY(d):
+ return d.subarray.shape
+ else:
+ return ()
+
+
+cdef extern from "numpy/ndarrayobject.h":
+ PyTypeObject PyTimedeltaArrType_Type
+ PyTypeObject PyDatetimeArrType_Type
+ ctypedef int64_t npy_timedelta
+ ctypedef int64_t npy_datetime
+
+cdef extern from "numpy/ndarraytypes.h":
+ ctypedef struct PyArray_DatetimeMetaData:
+ NPY_DATETIMEUNIT base
+ int64_t num
+
+cdef extern from "numpy/arrayscalars.h":
+
+ # abstract types
+ ctypedef class numpy.generic [object PyObject]:
+ pass
+ ctypedef class numpy.number [object PyObject]:
+ pass
+ ctypedef class numpy.integer [object PyObject]:
+ pass
+ ctypedef class numpy.signedinteger [object PyObject]:
+ pass
+ ctypedef class numpy.unsignedinteger [object PyObject]:
+ pass
+ ctypedef class numpy.inexact [object PyObject]:
+ pass
+ ctypedef class numpy.floating [object PyObject]:
+ pass
+ ctypedef class numpy.complexfloating [object PyObject]:
+ pass
+ ctypedef class numpy.flexible [object PyObject]:
+ pass
+ ctypedef class numpy.character [object PyObject]:
+ pass
+
+ ctypedef struct PyDatetimeScalarObject:
+ # PyObject_HEAD
+ npy_datetime obval
+ PyArray_DatetimeMetaData obmeta
+
+ ctypedef struct PyTimedeltaScalarObject:
+ # PyObject_HEAD
+ npy_timedelta obval
+ PyArray_DatetimeMetaData obmeta
+
+ ctypedef enum NPY_DATETIMEUNIT:
+ NPY_FR_Y
+ NPY_FR_M
+ NPY_FR_W
+ NPY_FR_D
+ NPY_FR_B
+ NPY_FR_h
+ NPY_FR_m
+ NPY_FR_s
+ NPY_FR_ms
+ NPY_FR_us
+ NPY_FR_ns
+ NPY_FR_ps
+ NPY_FR_fs
+ NPY_FR_as
+
+
+#
+# ufunc API
+#
+
+cdef extern from "numpy/ufuncobject.h":
+
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
+
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
+ cdef:
+ int nin, nout, nargs
+ int identity
+ PyUFuncGenericFunction *functions
+ void **data
+ int ntypes
+ int check_return
+ char *name
+ char *types
+ char *doc
+ void *ptr
+ PyObject *obj
+ PyObject *userloops
+
+ cdef enum:
+ PyUFunc_Zero
+ PyUFunc_One
+ PyUFunc_None
+ UFUNC_ERR_IGNORE
+ UFUNC_ERR_WARN
+ UFUNC_ERR_RAISE
+ UFUNC_ERR_CALL
+ UFUNC_ERR_PRINT
+ UFUNC_ERR_LOG
+ UFUNC_MASK_DIVIDEBYZERO
+ UFUNC_MASK_OVERFLOW
+ UFUNC_MASK_UNDERFLOW
+ UFUNC_MASK_INVALID
+ UFUNC_SHIFT_DIVIDEBYZERO
+ UFUNC_SHIFT_OVERFLOW
+ UFUNC_SHIFT_UNDERFLOW
+ UFUNC_SHIFT_INVALID
+ UFUNC_FPE_DIVIDEBYZERO
+ UFUNC_FPE_OVERFLOW
+ UFUNC_FPE_UNDERFLOW
+ UFUNC_FPE_INVALID
+ UFUNC_ERR_DEFAULT
+ UFUNC_ERR_DEFAULT2
+
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
+ void **, char *, int, int, int, int, char *, char *, int)
+ int PyUFunc_RegisterLoopForType(ufunc, int,
+ PyUFuncGenericFunction, int *, void *)
+ void PyUFunc_f_f_As_d_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_d_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_f_f \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_g_g \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_F_F_As_D_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_F_F \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_D_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_G_G \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_O_O \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_ff_f_As_dd_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_ff_f \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_dd_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_gg_g \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_FF_F_As_DD_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_DD_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_FF_F \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_GG_G \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_OO_O \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_O_O_method \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_OO_O_method \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_On_Om \
+ (char **, npy_intp *, npy_intp *, void *)
+ int PyUFunc_GetPyValues \
+ (char *, int *, int *, PyObject **)
+ int PyUFunc_checkfperr \
+ (int, PyObject *, int *)
+ void PyUFunc_clearfperr()
+ int PyUFunc_getfperr()
+ int PyUFunc_handlefperr \
+ (int, PyObject *, int, int *)
+ int PyUFunc_ReplaceLoopBySignature \
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
+ object PyUFunc_FromFuncAndDataAndSignature \
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
+ int, char *, char *, int, char *)
+
+ int _import_umath() except -1
+
+cdef inline void set_array_base(ndarray arr, object base):
+ Py_INCREF(base) # important to do this before stealing the reference below!
+ PyArray_SetBaseObject(arr, base)
+
+cdef inline object get_array_base(ndarray arr):
+ base = PyArray_BASE(arr)
+ if base is NULL:
+ return None
+ return base
+
+# Versions of the import_* functions which are more suitable for
+# Cython code.
+cdef inline int import_array() except -1:
+ try:
+ __pyx_import_array()
+ except Exception:
+ raise ImportError("numpy.core.multiarray failed to import")
+
+cdef inline int import_umath() except -1:
+ try:
+ _import_umath()
+ except Exception:
+ raise ImportError("numpy.core.umath failed to import")
+
+cdef inline int import_ufunc() except -1:
+ try:
+ _import_umath()
+ except Exception:
+ raise ImportError("numpy.core.umath failed to import")
+
+
+cdef inline bint is_timedelta64_object(object obj):
+ """
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
+
+ Parameters
+ ----------
+ obj : object
+
+ Returns
+ -------
+ bool
+ """
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
+
+
+cdef inline bint is_datetime64_object(object obj):
+ """
+ Cython equivalent of `isinstance(obj, np.datetime64)`
+
+ Parameters
+ ----------
+ obj : object
+
+ Returns
+ -------
+ bool
+ """
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
+
+
+cdef inline npy_datetime get_datetime64_value(object obj) nogil:
+ """
+ returns the int64 value underlying scalar numpy datetime64 object
+
+ Note that to interpret this as a datetime, the corresponding unit is
+ also needed. That can be found using `get_datetime64_unit`.
+ """
+ return (obj).obval
+
+
+cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
+ """
+ returns the int64 value underlying scalar numpy timedelta64 object
+ """
+ return (obj).obval
+
+
+cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
+ """
+ returns the unit part of the dtype for a numpy datetime64 object.
+ """
+ return (obj).obmeta.base
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pxd b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..03db9a0c12fa44a059916442404535bec6a543eb
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pxd
@@ -0,0 +1,1017 @@
+# NumPy static imports for Cython < 3.0
+#
+# If any of the PyArray_* functions are called, import_array must be
+# called first.
+#
+# Author: Dag Sverre Seljebotn
+#
+
+DEF _buffer_format_string_len = 255
+
+cimport cpython.buffer as pybuf
+from cpython.ref cimport Py_INCREF
+from cpython.mem cimport PyObject_Malloc, PyObject_Free
+from cpython.object cimport PyObject, PyTypeObject
+from cpython.buffer cimport PyObject_GetBuffer
+from cpython.type cimport type
+cimport libc.stdio as stdio
+
+cdef extern from "Python.h":
+ ctypedef int Py_intptr_t
+ bint PyObject_TypeCheck(object obj, PyTypeObject* type)
+
+cdef extern from "numpy/arrayobject.h":
+ ctypedef Py_intptr_t npy_intp
+ ctypedef size_t npy_uintp
+
+ cdef enum NPY_TYPES:
+ NPY_BOOL
+ NPY_BYTE
+ NPY_UBYTE
+ NPY_SHORT
+ NPY_USHORT
+ NPY_INT
+ NPY_UINT
+ NPY_LONG
+ NPY_ULONG
+ NPY_LONGLONG
+ NPY_ULONGLONG
+ NPY_FLOAT
+ NPY_DOUBLE
+ NPY_LONGDOUBLE
+ NPY_CFLOAT
+ NPY_CDOUBLE
+ NPY_CLONGDOUBLE
+ NPY_OBJECT
+ NPY_STRING
+ NPY_UNICODE
+ NPY_VOID
+ NPY_DATETIME
+ NPY_TIMEDELTA
+ NPY_NTYPES
+ NPY_NOTYPE
+
+ NPY_INT8
+ NPY_INT16
+ NPY_INT32
+ NPY_INT64
+ NPY_INT128
+ NPY_INT256
+ NPY_UINT8
+ NPY_UINT16
+ NPY_UINT32
+ NPY_UINT64
+ NPY_UINT128
+ NPY_UINT256
+ NPY_FLOAT16
+ NPY_FLOAT32
+ NPY_FLOAT64
+ NPY_FLOAT80
+ NPY_FLOAT96
+ NPY_FLOAT128
+ NPY_FLOAT256
+ NPY_COMPLEX32
+ NPY_COMPLEX64
+ NPY_COMPLEX128
+ NPY_COMPLEX160
+ NPY_COMPLEX192
+ NPY_COMPLEX256
+ NPY_COMPLEX512
+
+ NPY_INTP
+
+ ctypedef enum NPY_ORDER:
+ NPY_ANYORDER
+ NPY_CORDER
+ NPY_FORTRANORDER
+ NPY_KEEPORDER
+
+ ctypedef enum NPY_CASTING:
+ NPY_NO_CASTING
+ NPY_EQUIV_CASTING
+ NPY_SAFE_CASTING
+ NPY_SAME_KIND_CASTING
+ NPY_UNSAFE_CASTING
+
+ ctypedef enum NPY_CLIPMODE:
+ NPY_CLIP
+ NPY_WRAP
+ NPY_RAISE
+
+ ctypedef enum NPY_SCALARKIND:
+ NPY_NOSCALAR,
+ NPY_BOOL_SCALAR,
+ NPY_INTPOS_SCALAR,
+ NPY_INTNEG_SCALAR,
+ NPY_FLOAT_SCALAR,
+ NPY_COMPLEX_SCALAR,
+ NPY_OBJECT_SCALAR
+
+ ctypedef enum NPY_SORTKIND:
+ NPY_QUICKSORT
+ NPY_HEAPSORT
+ NPY_MERGESORT
+
+ ctypedef enum NPY_SEARCHSIDE:
+ NPY_SEARCHLEFT
+ NPY_SEARCHRIGHT
+
+ enum:
+ # DEPRECATED since NumPy 1.7 ! Do not use in new code!
+ NPY_C_CONTIGUOUS
+ NPY_F_CONTIGUOUS
+ NPY_CONTIGUOUS
+ NPY_FORTRAN
+ NPY_OWNDATA
+ NPY_FORCECAST
+ NPY_ENSURECOPY
+ NPY_ENSUREARRAY
+ NPY_ELEMENTSTRIDES
+ NPY_ALIGNED
+ NPY_NOTSWAPPED
+ NPY_WRITEABLE
+ NPY_ARR_HAS_DESCR
+
+ NPY_BEHAVED
+ NPY_BEHAVED_NS
+ NPY_CARRAY
+ NPY_CARRAY_RO
+ NPY_FARRAY
+ NPY_FARRAY_RO
+ NPY_DEFAULT
+
+ NPY_IN_ARRAY
+ NPY_OUT_ARRAY
+ NPY_INOUT_ARRAY
+ NPY_IN_FARRAY
+ NPY_OUT_FARRAY
+ NPY_INOUT_FARRAY
+
+ NPY_UPDATE_ALL
+
+ enum:
+ # Added in NumPy 1.7 to replace the deprecated enums above.
+ NPY_ARRAY_C_CONTIGUOUS
+ NPY_ARRAY_F_CONTIGUOUS
+ NPY_ARRAY_OWNDATA
+ NPY_ARRAY_FORCECAST
+ NPY_ARRAY_ENSURECOPY
+ NPY_ARRAY_ENSUREARRAY
+ NPY_ARRAY_ELEMENTSTRIDES
+ NPY_ARRAY_ALIGNED
+ NPY_ARRAY_NOTSWAPPED
+ NPY_ARRAY_WRITEABLE
+ NPY_ARRAY_WRITEBACKIFCOPY
+
+ NPY_ARRAY_BEHAVED
+ NPY_ARRAY_BEHAVED_NS
+ NPY_ARRAY_CARRAY
+ NPY_ARRAY_CARRAY_RO
+ NPY_ARRAY_FARRAY
+ NPY_ARRAY_FARRAY_RO
+ NPY_ARRAY_DEFAULT
+
+ NPY_ARRAY_IN_ARRAY
+ NPY_ARRAY_OUT_ARRAY
+ NPY_ARRAY_INOUT_ARRAY
+ NPY_ARRAY_IN_FARRAY
+ NPY_ARRAY_OUT_FARRAY
+ NPY_ARRAY_INOUT_FARRAY
+
+ NPY_ARRAY_UPDATE_ALL
+
+ cdef enum:
+ NPY_MAXDIMS
+
+ npy_intp NPY_MAX_ELSIZE
+
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
+
+ ctypedef struct PyArray_ArrayDescr:
+ # shape is a tuple, but Cython doesn't support "tuple shape"
+ # inside a non-PyObject declaration, so we have to declare it
+ # as just a PyObject*.
+ PyObject* shape
+
+ ctypedef struct PyArray_Descr:
+ pass
+
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
+ # Use PyDataType_* macros when possible, however there are no macros
+ # for accessing some of the fields, so some are defined.
+ cdef PyTypeObject* typeobj
+ cdef char kind
+ cdef char type
+ # Numpy sometimes mutates this without warning (e.g. it'll
+ # sometimes change "|" to "<" in shared dtype objects on
+ # little-endian machines). If this matters to you, use
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
+ # directly accessing this field.
+ cdef char byteorder
+ cdef char flags
+ cdef int type_num
+ cdef int itemsize "elsize"
+ cdef int alignment
+ cdef object fields
+ cdef tuple names
+ # Use PyDataType_HASSUBARRAY to test whether this field is
+ # valid (the pointer can be NULL). Most users should access
+ # this field via the inline helper method PyDataType_SHAPE.
+ cdef PyArray_ArrayDescr* subarray
+
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
+ # Use through macros
+ pass
+
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
+ cdef int numiter
+ cdef npy_intp size, index
+ cdef int nd
+ cdef npy_intp *dimensions
+ cdef void **iters
+
+ ctypedef struct PyArrayObject:
+ # For use in situations where ndarray can't replace PyArrayObject*,
+ # like PyArrayObject**.
+ pass
+
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
+
+ cdef:
+ # Only taking a few of the most commonly used and stable fields.
+ # One should use PyArray_* macros instead to access the C fields.
+ char *data
+ int ndim "nd"
+ npy_intp *shape "dimensions"
+ npy_intp *strides
+ dtype descr # deprecated since NumPy 1.7 !
+ PyObject* base # NOT PUBLIC, DO NOT USE !
+
+
+
+ ctypedef unsigned char npy_bool
+
+ ctypedef signed char npy_byte
+ ctypedef signed short npy_short
+ ctypedef signed int npy_int
+ ctypedef signed long npy_long
+ ctypedef signed long long npy_longlong
+
+ ctypedef unsigned char npy_ubyte
+ ctypedef unsigned short npy_ushort
+ ctypedef unsigned int npy_uint
+ ctypedef unsigned long npy_ulong
+ ctypedef unsigned long long npy_ulonglong
+
+ ctypedef float npy_float
+ ctypedef double npy_double
+ ctypedef long double npy_longdouble
+
+ ctypedef signed char npy_int8
+ ctypedef signed short npy_int16
+ ctypedef signed int npy_int32
+ ctypedef signed long long npy_int64
+ ctypedef signed long long npy_int96
+ ctypedef signed long long npy_int128
+
+ ctypedef unsigned char npy_uint8
+ ctypedef unsigned short npy_uint16
+ ctypedef unsigned int npy_uint32
+ ctypedef unsigned long long npy_uint64
+ ctypedef unsigned long long npy_uint96
+ ctypedef unsigned long long npy_uint128
+
+ ctypedef float npy_float32
+ ctypedef double npy_float64
+ ctypedef long double npy_float80
+ ctypedef long double npy_float96
+ ctypedef long double npy_float128
+
+ ctypedef struct npy_cfloat:
+ float real
+ float imag
+
+ ctypedef struct npy_cdouble:
+ double real
+ double imag
+
+ ctypedef struct npy_clongdouble:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex64:
+ float real
+ float imag
+
+ ctypedef struct npy_complex128:
+ double real
+ double imag
+
+ ctypedef struct npy_complex160:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex192:
+ long double real
+ long double imag
+
+ ctypedef struct npy_complex256:
+ long double real
+ long double imag
+
+ ctypedef struct PyArray_Dims:
+ npy_intp *ptr
+ int len
+
+ int _import_array() except -1
+ # A second definition so _import_array isn't marked as used when we use it here.
+ # Do not use - subject to change any time.
+ int __pyx_import_array "_import_array"() except -1
+
+ #
+ # Macros from ndarrayobject.h
+ #
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
+ bint PyArray_ISALIGNED(ndarray m) nogil
+
+ int PyArray_NDIM(ndarray) nogil
+ bint PyArray_ISONESEGMENT(ndarray) nogil
+ bint PyArray_ISFORTRAN(ndarray) nogil
+ int PyArray_FORTRANIF(ndarray) nogil
+
+ void* PyArray_DATA(ndarray) nogil
+ char* PyArray_BYTES(ndarray) nogil
+
+ npy_intp* PyArray_DIMS(ndarray) nogil
+ npy_intp* PyArray_STRIDES(ndarray) nogil
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
+
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
+ int PyArray_FLAGS(ndarray) nogil
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
+ int PyArray_TYPE(ndarray arr) nogil
+
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj)
+
+ bint PyTypeNum_ISBOOL(int) nogil
+ bint PyTypeNum_ISUNSIGNED(int) nogil
+ bint PyTypeNum_ISSIGNED(int) nogil
+ bint PyTypeNum_ISINTEGER(int) nogil
+ bint PyTypeNum_ISFLOAT(int) nogil
+ bint PyTypeNum_ISNUMBER(int) nogil
+ bint PyTypeNum_ISSTRING(int) nogil
+ bint PyTypeNum_ISCOMPLEX(int) nogil
+ bint PyTypeNum_ISPYTHON(int) nogil
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
+ bint PyTypeNum_ISUSERDEF(int) nogil
+ bint PyTypeNum_ISEXTENDED(int) nogil
+ bint PyTypeNum_ISOBJECT(int) nogil
+
+ bint PyDataType_ISBOOL(dtype) nogil
+ bint PyDataType_ISUNSIGNED(dtype) nogil
+ bint PyDataType_ISSIGNED(dtype) nogil
+ bint PyDataType_ISINTEGER(dtype) nogil
+ bint PyDataType_ISFLOAT(dtype) nogil
+ bint PyDataType_ISNUMBER(dtype) nogil
+ bint PyDataType_ISSTRING(dtype) nogil
+ bint PyDataType_ISCOMPLEX(dtype) nogil
+ bint PyDataType_ISPYTHON(dtype) nogil
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
+ bint PyDataType_ISUSERDEF(dtype) nogil
+ bint PyDataType_ISEXTENDED(dtype) nogil
+ bint PyDataType_ISOBJECT(dtype) nogil
+ bint PyDataType_HASFIELDS(dtype) nogil
+ bint PyDataType_HASSUBARRAY(dtype) nogil
+
+ bint PyArray_ISBOOL(ndarray) nogil
+ bint PyArray_ISUNSIGNED(ndarray) nogil
+ bint PyArray_ISSIGNED(ndarray) nogil
+ bint PyArray_ISINTEGER(ndarray) nogil
+ bint PyArray_ISFLOAT(ndarray) nogil
+ bint PyArray_ISNUMBER(ndarray) nogil
+ bint PyArray_ISSTRING(ndarray) nogil
+ bint PyArray_ISCOMPLEX(ndarray) nogil
+ bint PyArray_ISPYTHON(ndarray) nogil
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
+ bint PyArray_ISUSERDEF(ndarray) nogil
+ bint PyArray_ISEXTENDED(ndarray) nogil
+ bint PyArray_ISOBJECT(ndarray) nogil
+ bint PyArray_HASFIELDS(ndarray) nogil
+
+ bint PyArray_ISVARIABLE(ndarray) nogil
+
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
+
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
+
+ bint PyArray_ISCARRAY(ndarray) nogil
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
+ bint PyArray_ISFARRAY(ndarray) nogil
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
+ bint PyArray_ISBEHAVED(ndarray) nogil
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
+
+
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
+
+ bint PyArray_DescrCheck(object)
+
+ bint PyArray_Check(object)
+ bint PyArray_CheckExact(object)
+
+ # Cannot be supported due to out arg:
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
+ # bint PyArray_HasArrayInterface(op, out)
+
+
+ bint PyArray_IsZeroDim(object)
+ # Cannot be supported due to ## ## in macro:
+ # bint PyArray_IsScalar(object, verbatim work)
+ bint PyArray_CheckScalar(object)
+ bint PyArray_IsPythonNumber(object)
+ bint PyArray_IsPythonScalar(object)
+ bint PyArray_IsAnyScalar(object)
+ bint PyArray_CheckAnyScalar(object)
+
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
+ npy_intp PyArray_SIZE(ndarray) nogil
+ npy_intp PyArray_NBYTES(ndarray) nogil
+
+ object PyArray_FROM_O(object)
+ object PyArray_FROM_OF(object m, int flags)
+ object PyArray_FROM_OT(object m, int type)
+ object PyArray_FROM_OTF(object m, int type, int flags)
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
+ void PyArray_FILLWBYTE(object, int val)
+ npy_intp PyArray_REFCOUNT(object)
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
+ object PyArray_ToScalar(void* data, ndarray arr)
+
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
+
+ void PyArray_XDECREF_ERR(ndarray)
+ # Cannot be supported due to out arg
+ # void PyArray_DESCR_REPLACE(descr)
+
+
+ object PyArray_Copy(ndarray)
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
+
+ object PyArray_Cast(ndarray mp, int type_num)
+ object PyArray_Take(ndarray ap, object items, int axis)
+ object PyArray_Put(ndarray ap, object items, object values)
+
+ void PyArray_ITER_RESET(flatiter it) nogil
+ void PyArray_ITER_NEXT(flatiter it) nogil
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
+ void* PyArray_ITER_DATA(flatiter it) nogil
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
+
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
+
+ # Functions from __multiarray_api.h
+
+ # Functions taking dtype and returning object/ndarray are disabled
+ # for now as they steal dtype references. I'm conservative and disable
+ # more than is probably needed until it can be checked further.
+ int PyArray_SetNumericOps (object)
+ object PyArray_GetNumericOps ()
+ int PyArray_INCREF (ndarray)
+ int PyArray_XDECREF (ndarray)
+ void PyArray_SetStringFunction (object, int)
+ dtype PyArray_DescrFromType (int)
+ object PyArray_TypeObjectFromType (int)
+ char * PyArray_Zero (ndarray)
+ char * PyArray_One (ndarray)
+ #object PyArray_CastToType (ndarray, dtype, int)
+ int PyArray_CastTo (ndarray, ndarray)
+ int PyArray_CastAnyTo (ndarray, ndarray)
+ int PyArray_CanCastSafely (int, int)
+ npy_bool PyArray_CanCastTo (dtype, dtype)
+ int PyArray_ObjectType (object, int)
+ dtype PyArray_DescrFromObject (object, dtype)
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
+ dtype PyArray_DescrFromScalar (object)
+ dtype PyArray_DescrFromTypeObject (object)
+ npy_intp PyArray_Size (object)
+ #object PyArray_Scalar (void *, dtype, object)
+ #object PyArray_FromScalar (object, dtype)
+ void PyArray_ScalarAsCtype (object, void *)
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
+ object PyArray_ScalarFromObject (object)
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
+ object PyArray_FromDims (int, int *, int)
+ #object PyArray_FromDimsAndDataAndDescr (int, int *, dtype, char *)
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
+ object PyArray_EnsureArray (object)
+ object PyArray_EnsureAnyArray (object)
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
+ #object PyArray_FromIter (object, dtype, npy_intp)
+ object PyArray_Return (ndarray)
+ #object PyArray_GetField (ndarray, dtype, int)
+ #int PyArray_SetField (ndarray, dtype, int, object)
+ object PyArray_Byteswap (ndarray, npy_bool)
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
+ int PyArray_MoveInto (ndarray, ndarray)
+ int PyArray_CopyInto (ndarray, ndarray)
+ int PyArray_CopyAnyInto (ndarray, ndarray)
+ int PyArray_CopyObject (ndarray, object)
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
+ object PyArray_ToList (ndarray)
+ object PyArray_ToString (ndarray, NPY_ORDER)
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *)
+ int PyArray_Dump (object, object, int)
+ object PyArray_Dumps (object, int)
+ int PyArray_ValidType (int)
+ void PyArray_UpdateFlags (ndarray, int)
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
+ #dtype PyArray_DescrNew (dtype)
+ dtype PyArray_DescrNewFromType (int)
+ double PyArray_GetPriority (object, double)
+ object PyArray_IterNew (object)
+ object PyArray_MultiIterNew (int, ...)
+
+ int PyArray_PyIntAsInt (object)
+ npy_intp PyArray_PyIntAsIntp (object)
+ int PyArray_Broadcast (broadcast)
+ void PyArray_FillObjectArray (ndarray, object)
+ int PyArray_FillWithScalar (ndarray, object)
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
+ dtype PyArray_DescrNewByteorder (dtype, char)
+ object PyArray_IterAllButAxis (object, int *)
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
+ #object PyArray_FromArray (ndarray, dtype, int)
+ object PyArray_FromInterface (object)
+ object PyArray_FromStructInterface (object)
+ #object PyArray_FromArrayAttr (object, dtype, object)
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
+ object PyArray_NewFlagsObject (object)
+ npy_bool PyArray_CanCastScalar (type, type)
+ #int PyArray_CompareUCS4 (npy_ucs4 *, npy_ucs4 *, register size_t)
+ int PyArray_RemoveSmallest (broadcast)
+ int PyArray_ElementStrides (object)
+ void PyArray_Item_INCREF (char *, dtype)
+ void PyArray_Item_XDECREF (char *, dtype)
+ object PyArray_FieldNames (object)
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
+ object PyArray_PutMask (ndarray, object, object)
+ object PyArray_Repeat (ndarray, object, int)
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND)
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
+ object PyArray_ArgMax (ndarray, int, ndarray)
+ object PyArray_ArgMin (ndarray, int, ndarray)
+ object PyArray_Reshape (ndarray, object)
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
+ object PyArray_Squeeze (ndarray)
+ #object PyArray_View (ndarray, dtype, type)
+ object PyArray_SwapAxes (ndarray, int, int)
+ object PyArray_Max (ndarray, int, ndarray)
+ object PyArray_Min (ndarray, int, ndarray)
+ object PyArray_Ptp (ndarray, int, ndarray)
+ object PyArray_Mean (ndarray, int, int, ndarray)
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
+ object PyArray_Diagonal (ndarray, int, int, int)
+ object PyArray_Clip (ndarray, object, object, ndarray)
+ object PyArray_Conjugate (ndarray, ndarray)
+ object PyArray_Nonzero (ndarray)
+ object PyArray_Std (ndarray, int, int, ndarray, int)
+ object PyArray_Sum (ndarray, int, int, ndarray)
+ object PyArray_CumSum (ndarray, int, int, ndarray)
+ object PyArray_Prod (ndarray, int, int, ndarray)
+ object PyArray_CumProd (ndarray, int, int, ndarray)
+ object PyArray_All (ndarray, int, ndarray)
+ object PyArray_Any (ndarray, int, ndarray)
+ object PyArray_Compress (ndarray, object, int, ndarray)
+ object PyArray_Flatten (ndarray, NPY_ORDER)
+ object PyArray_Ravel (ndarray, NPY_ORDER)
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
+ int PyArray_MultiplyIntList (int *, int)
+ void * PyArray_GetPtr (ndarray, npy_intp*)
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
+ #int PyArray_As1D (object*, char **, int *, int)
+ #int PyArray_As2D (object*, char ***, int *, int *, int)
+ int PyArray_Free (object, void *)
+ #int PyArray_Converter (object, object*)
+ int PyArray_IntpFromSequence (object, npy_intp *, int)
+ object PyArray_Concatenate (object, int)
+ object PyArray_InnerProduct (object, object)
+ object PyArray_MatrixProduct (object, object)
+ object PyArray_CopyAndTranspose (object)
+ object PyArray_Correlate (object, object, int)
+ int PyArray_TypestrConvert (int, int)
+ #int PyArray_DescrConverter (object, dtype*)
+ #int PyArray_DescrConverter2 (object, dtype*)
+ int PyArray_IntpConverter (object, PyArray_Dims *)
+ #int PyArray_BufferConverter (object, chunk)
+ int PyArray_AxisConverter (object, int *)
+ int PyArray_BoolConverter (object, npy_bool *)
+ int PyArray_ByteorderConverter (object, char *)
+ int PyArray_OrderConverter (object, NPY_ORDER *)
+ unsigned char PyArray_EquivTypes (dtype, dtype)
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
+ object PyArray_Where (object, object, object)
+ object PyArray_Arange (double, double, double, int)
+ #object PyArray_ArangeObj (object, object, object, dtype)
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *)
+ object PyArray_LexSort (object, int)
+ object PyArray_Round (ndarray, int, ndarray)
+ unsigned char PyArray_EquivTypenums (int, int)
+ int PyArray_RegisterDataType (dtype)
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *)
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND)
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
+ int PyArray_TypeNumFromName (char *)
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *)
+ #int PyArray_OutputConverter (object, ndarray*)
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
+ void _PyArray_SigintHandler (int)
+ void* _PyArray_GetSigintBuf ()
+ #int PyArray_DescrAlignConverter (object, dtype*)
+ #int PyArray_DescrAlignConverter2 (object, dtype*)
+ int PyArray_SearchsideConverter (object, void *)
+ object PyArray_CheckAxis (ndarray, int *, int)
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
+ int PyArray_CompareString (char *, char *, size_t)
+ int PyArray_SetBaseObject(ndarray, base) # NOTE: steals a reference to base! Use "set_array_base()" instead.
+
+
+# Typedefs that matches the runtime dtype objects in
+# the numpy module.
+
+# The ones that are commented out needs an IFDEF function
+# in Cython to enable them only on the right systems.
+
+ctypedef npy_int8 int8_t
+ctypedef npy_int16 int16_t
+ctypedef npy_int32 int32_t
+ctypedef npy_int64 int64_t
+#ctypedef npy_int96 int96_t
+#ctypedef npy_int128 int128_t
+
+ctypedef npy_uint8 uint8_t
+ctypedef npy_uint16 uint16_t
+ctypedef npy_uint32 uint32_t
+ctypedef npy_uint64 uint64_t
+#ctypedef npy_uint96 uint96_t
+#ctypedef npy_uint128 uint128_t
+
+ctypedef npy_float32 float32_t
+ctypedef npy_float64 float64_t
+#ctypedef npy_float80 float80_t
+#ctypedef npy_float128 float128_t
+
+ctypedef float complex complex64_t
+ctypedef double complex complex128_t
+
+# The int types are mapped a bit surprising --
+# numpy.int corresponds to 'l' and numpy.long to 'q'
+ctypedef npy_long int_t
+ctypedef npy_longlong long_t
+ctypedef npy_longlong longlong_t
+
+ctypedef npy_ulong uint_t
+ctypedef npy_ulonglong ulong_t
+ctypedef npy_ulonglong ulonglong_t
+
+ctypedef npy_intp intp_t
+ctypedef npy_uintp uintp_t
+
+ctypedef npy_double float_t
+ctypedef npy_double double_t
+ctypedef npy_longdouble longdouble_t
+
+ctypedef npy_cfloat cfloat_t
+ctypedef npy_cdouble cdouble_t
+ctypedef npy_clongdouble clongdouble_t
+
+ctypedef npy_cdouble complex_t
+
+cdef inline object PyArray_MultiIterNew1(a):
+ return PyArray_MultiIterNew(1, a)
+
+cdef inline object PyArray_MultiIterNew2(a, b):
+ return PyArray_MultiIterNew(2, a, b)
+
+cdef inline object PyArray_MultiIterNew3(a, b, c):
+ return PyArray_MultiIterNew(3, a, b, c)
+
+cdef inline object PyArray_MultiIterNew4(a, b, c, d):
+ return PyArray_MultiIterNew(4, a, b, c, d)
+
+cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
+ return PyArray_MultiIterNew(5, a, b, c, d, e)
+
+cdef inline tuple PyDataType_SHAPE(dtype d):
+ if PyDataType_HASSUBARRAY(d):
+ return d.subarray.shape
+ else:
+ return ()
+
+
+cdef extern from "numpy/ndarrayobject.h":
+ PyTypeObject PyTimedeltaArrType_Type
+ PyTypeObject PyDatetimeArrType_Type
+ ctypedef int64_t npy_timedelta
+ ctypedef int64_t npy_datetime
+
+cdef extern from "numpy/ndarraytypes.h":
+ ctypedef struct PyArray_DatetimeMetaData:
+ NPY_DATETIMEUNIT base
+ int64_t num
+
+cdef extern from "numpy/arrayscalars.h":
+
+ # abstract types
+ ctypedef class numpy.generic [object PyObject]:
+ pass
+ ctypedef class numpy.number [object PyObject]:
+ pass
+ ctypedef class numpy.integer [object PyObject]:
+ pass
+ ctypedef class numpy.signedinteger [object PyObject]:
+ pass
+ ctypedef class numpy.unsignedinteger [object PyObject]:
+ pass
+ ctypedef class numpy.inexact [object PyObject]:
+ pass
+ ctypedef class numpy.floating [object PyObject]:
+ pass
+ ctypedef class numpy.complexfloating [object PyObject]:
+ pass
+ ctypedef class numpy.flexible [object PyObject]:
+ pass
+ ctypedef class numpy.character [object PyObject]:
+ pass
+
+ ctypedef struct PyDatetimeScalarObject:
+ # PyObject_HEAD
+ npy_datetime obval
+ PyArray_DatetimeMetaData obmeta
+
+ ctypedef struct PyTimedeltaScalarObject:
+ # PyObject_HEAD
+ npy_timedelta obval
+ PyArray_DatetimeMetaData obmeta
+
+ ctypedef enum NPY_DATETIMEUNIT:
+ NPY_FR_Y
+ NPY_FR_M
+ NPY_FR_W
+ NPY_FR_D
+ NPY_FR_B
+ NPY_FR_h
+ NPY_FR_m
+ NPY_FR_s
+ NPY_FR_ms
+ NPY_FR_us
+ NPY_FR_ns
+ NPY_FR_ps
+ NPY_FR_fs
+ NPY_FR_as
+
+
+#
+# ufunc API
+#
+
+cdef extern from "numpy/ufuncobject.h":
+
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
+
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
+ cdef:
+ int nin, nout, nargs
+ int identity
+ PyUFuncGenericFunction *functions
+ void **data
+ int ntypes
+ int check_return
+ char *name
+ char *types
+ char *doc
+ void *ptr
+ PyObject *obj
+ PyObject *userloops
+
+ cdef enum:
+ PyUFunc_Zero
+ PyUFunc_One
+ PyUFunc_None
+ UFUNC_ERR_IGNORE
+ UFUNC_ERR_WARN
+ UFUNC_ERR_RAISE
+ UFUNC_ERR_CALL
+ UFUNC_ERR_PRINT
+ UFUNC_ERR_LOG
+ UFUNC_MASK_DIVIDEBYZERO
+ UFUNC_MASK_OVERFLOW
+ UFUNC_MASK_UNDERFLOW
+ UFUNC_MASK_INVALID
+ UFUNC_SHIFT_DIVIDEBYZERO
+ UFUNC_SHIFT_OVERFLOW
+ UFUNC_SHIFT_UNDERFLOW
+ UFUNC_SHIFT_INVALID
+ UFUNC_FPE_DIVIDEBYZERO
+ UFUNC_FPE_OVERFLOW
+ UFUNC_FPE_UNDERFLOW
+ UFUNC_FPE_INVALID
+ UFUNC_ERR_DEFAULT
+ UFUNC_ERR_DEFAULT2
+
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
+ void **, char *, int, int, int, int, char *, char *, int)
+ int PyUFunc_RegisterLoopForType(ufunc, int,
+ PyUFuncGenericFunction, int *, void *)
+ void PyUFunc_f_f_As_d_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_d_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_f_f \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_g_g \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_F_F_As_D_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_F_F \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_D_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_G_G \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_O_O \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_ff_f_As_dd_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_ff_f \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_dd_d \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_gg_g \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_FF_F_As_DD_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_DD_D \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_FF_F \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_GG_G \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_OO_O \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_O_O_method \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_OO_O_method \
+ (char **, npy_intp *, npy_intp *, void *)
+ void PyUFunc_On_Om \
+ (char **, npy_intp *, npy_intp *, void *)
+ int PyUFunc_GetPyValues \
+ (char *, int *, int *, PyObject **)
+ int PyUFunc_checkfperr \
+ (int, PyObject *, int *)
+ void PyUFunc_clearfperr()
+ int PyUFunc_getfperr()
+ int PyUFunc_handlefperr \
+ (int, PyObject *, int, int *)
+ int PyUFunc_ReplaceLoopBySignature \
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
+ object PyUFunc_FromFuncAndDataAndSignature \
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
+ int, char *, char *, int, char *)
+
+ int _import_umath() except -1
+
+cdef inline void set_array_base(ndarray arr, object base):
+ Py_INCREF(base) # important to do this before stealing the reference below!
+ PyArray_SetBaseObject(arr, base)
+
+cdef inline object get_array_base(ndarray arr):
+ base = PyArray_BASE(arr)
+ if base is NULL:
+ return None
+ return base
+
+# Versions of the import_* functions which are more suitable for
+# Cython code.
+cdef inline int import_array() except -1:
+ try:
+ __pyx_import_array()
+ except Exception:
+ raise ImportError("numpy.core.multiarray failed to import")
+
+cdef inline int import_umath() except -1:
+ try:
+ _import_umath()
+ except Exception:
+ raise ImportError("numpy.core.umath failed to import")
+
+cdef inline int import_ufunc() except -1:
+ try:
+ _import_umath()
+ except Exception:
+ raise ImportError("numpy.core.umath failed to import")
+
+cdef extern from *:
+ # Leave a marker that the NumPy declarations came from this file
+ # See https://github.com/cython/cython/issues/3573
+ """
+ /* NumPy API declarations from "numpy/__init__.pxd" */
+ """
+
+
+cdef inline bint is_timedelta64_object(object obj):
+ """
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
+
+ Parameters
+ ----------
+ obj : object
+
+ Returns
+ -------
+ bool
+ """
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
+
+
+cdef inline bint is_datetime64_object(object obj):
+ """
+ Cython equivalent of `isinstance(obj, np.datetime64)`
+
+ Parameters
+ ----------
+ obj : object
+
+ Returns
+ -------
+ bool
+ """
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
+
+
+cdef inline npy_datetime get_datetime64_value(object obj) nogil:
+ """
+ returns the int64 value underlying scalar numpy datetime64 object
+
+ Note that to interpret this as a datetime, the corresponding unit is
+ also needed. That can be found using `get_datetime64_unit`.
+ """
+ return (obj).obval
+
+
+cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
+ """
+ returns the int64 value underlying scalar numpy timedelta64 object
+ """
+ return (obj).obval
+
+
+cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
+ """
+ returns the unit part of the dtype for a numpy datetime64 object.
+ """
+ return (obj).obmeta.base
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e20a83ab1e7b5746e4473b786e572f02dba1a548
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.py
@@ -0,0 +1,439 @@
+"""
+NumPy
+=====
+
+Provides
+ 1. An array object of arbitrary homogeneous items
+ 2. Fast mathematical operations over arrays
+ 3. Linear Algebra, Fourier Transforms, Random Number Generation
+
+How to use the documentation
+----------------------------
+Documentation is available in two forms: docstrings provided
+with the code, and a loose standing reference guide, available from
+`the NumPy homepage `_.
+
+We recommend exploring the docstrings using
+`IPython `_, an advanced Python shell with
+TAB-completion and introspection capabilities. See below for further
+instructions.
+
+The docstring examples assume that `numpy` has been imported as ``np``::
+
+ >>> import numpy as np
+
+Code snippets are indicated by three greater-than signs::
+
+ >>> x = 42
+ >>> x = x + 1
+
+Use the built-in ``help`` function to view a function's docstring::
+
+ >>> help(np.sort)
+ ... # doctest: +SKIP
+
+For some objects, ``np.info(obj)`` may provide additional help. This is
+particularly true if you see the line "Help on ufunc object:" at the top
+of the help() page. Ufuncs are implemented in C, not Python, for speed.
+The native Python help() does not know how to view their help, but our
+np.info() function does.
+
+To search for documents containing a keyword, do::
+
+ >>> np.lookfor('keyword')
+ ... # doctest: +SKIP
+
+General-purpose documents like a glossary and help on the basic concepts
+of numpy are available under the ``doc`` sub-module::
+
+ >>> from numpy import doc
+ >>> help(doc)
+ ... # doctest: +SKIP
+
+Available subpackages
+---------------------
+lib
+ Basic functions used by several sub-packages.
+random
+ Core Random Tools
+linalg
+ Core Linear Algebra Tools
+fft
+ Core FFT routines
+polynomial
+ Polynomial tools
+testing
+ NumPy testing tools
+distutils
+ Enhancements to distutils with support for
+ Fortran compilers support and more.
+
+Utilities
+---------
+test
+ Run numpy unittests
+show_config
+ Show numpy build configuration
+dual
+ Overwrite certain functions with high-performance SciPy tools.
+ Note: `numpy.dual` is deprecated. Use the functions from NumPy or Scipy
+ directly instead of importing them from `numpy.dual`.
+matlib
+ Make everything matrices.
+__version__
+ NumPy version string
+
+Viewing documentation using IPython
+-----------------------------------
+
+Start IPython and import `numpy` usually under the alias ``np``: `import
+numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
+examples into the shell. To see which functions are available in `numpy`,
+type ``np.`` (where ```` refers to the TAB key), or use
+``np.*cos*?`` (where ```` refers to the ENTER key) to narrow
+down the list. To view the docstring for a function, use
+``np.cos?`` (to view the docstring) and ``np.cos??`` (to view
+the source code).
+
+Copies vs. in-place operation
+-----------------------------
+Most of the functions in `numpy` return a copy of the array argument
+(e.g., `np.sort`). In-place versions of these functions are often
+available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
+Exceptions to this rule are documented.
+
+"""
+import sys
+import warnings
+
+from ._globals import (
+ ModuleDeprecationWarning, VisibleDeprecationWarning,
+ _NoValue, _CopyMode
+)
+
+# We first need to detect if we're being called as part of the numpy setup
+# procedure itself in a reliable manner.
+try:
+ __NUMPY_SETUP__
+except NameError:
+ __NUMPY_SETUP__ = False
+
+if __NUMPY_SETUP__:
+ sys.stderr.write('Running from numpy source directory.\n')
+else:
+ try:
+ from numpy.__config__ import show as show_config
+ except ImportError as e:
+ msg = """Error importing numpy: you should not try to import numpy from
+ its source directory; please exit the numpy source tree, and relaunch
+ your python interpreter from there."""
+ raise ImportError(msg) from e
+
+ __all__ = ['ModuleDeprecationWarning',
+ 'VisibleDeprecationWarning']
+
+ # mapping of {name: (value, deprecation_msg)}
+ __deprecated_attrs__ = {}
+
+ # Allow distributors to run custom init code
+ from . import _distributor_init
+
+ from . import core
+ from .core import *
+ from . import compat
+ from . import lib
+ # NOTE: to be revisited following future namespace cleanup.
+ # See gh-14454 and gh-15672 for discussion.
+ from .lib import *
+
+ from . import linalg
+ from . import fft
+ from . import polynomial
+ from . import random
+ from . import ctypeslib
+ from . import ma
+ from . import matrixlib as _mat
+ from .matrixlib import *
+
+ # Deprecations introduced in NumPy 1.20.0, 2020-06-06
+ import builtins as _builtins
+
+ _msg = (
+ "module 'numpy' has no attribute '{n}'.\n"
+ "`np.{n}` was a deprecated alias for the builtin `{n}`. "
+ "To avoid this error in existing code, use `{n}` by itself. "
+ "Doing this will not modify any behavior and is safe. {extended_msg}\n"
+ "The aliases was originally deprecated in NumPy 1.20; for more "
+ "details and guidance see the original release note at:\n"
+ " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
+
+ _specific_msg = (
+ "If you specifically wanted the numpy scalar type, use `np.{}` here.")
+
+ _int_extended_msg = (
+ "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
+ "or `np.int32` to specify the precision. If you wish to review "
+ "your current use, check the release note link for "
+ "additional information.")
+
+ _type_info = [
+ ("object", ""), # The NumPy scalar only exists by name.
+ ("bool", _specific_msg.format("bool_")),
+ ("float", _specific_msg.format("float64")),
+ ("complex", _specific_msg.format("complex128")),
+ ("str", _specific_msg.format("str_")),
+ ("int", _int_extended_msg.format("int"))]
+
+ __former_attrs__ = {
+ n: _msg.format(n=n, extended_msg=extended_msg)
+ for n, extended_msg in _type_info
+ }
+
+ # Future warning introduced in NumPy 1.24.0, 2022-11-17
+ _msg = (
+ "`np.{n}` is a deprecated alias for `{an}`. (Deprecated NumPy 1.24)")
+
+ # Some of these are awkward (since `np.str` may be preferable in the long
+ # term), but overall the names ending in 0 seem undesireable
+ _type_info = [
+ ("bool8", bool_, "np.bool_"),
+ ("int0", intp, "np.intp"),
+ ("uint0", uintp, "np.uintp"),
+ ("str0", str_, "np.str_"),
+ ("bytes0", bytes_, "np.bytes_"),
+ ("void0", void, "np.void"),
+ ("object0", object_,
+ "`np.object0` is a deprecated alias for `np.object_`. "
+ "`object` can be used instead. (Deprecated NumPy 1.24)")]
+
+ # Some of these could be defined right away, but most were aliases to
+ # the Python objects and only removed in NumPy 1.24. Defining them should
+ # probably wait for NumPy 1.26 or 2.0.
+ # When defined, these should possibly not be added to `__all__` to avoid
+ # import with `from numpy import *`.
+ __future_scalars__ = {"bool", "long", "ulong", "str", "bytes", "object"}
+
+ __deprecated_attrs__.update({
+ n: (alias, _msg.format(n=n, an=an)) for n, alias, an in _type_info})
+
+ del _msg, _type_info
+
+ from .core import round, abs, max, min
+ # now that numpy modules are imported, can initialize limits
+ core.getlimits._register_known_types()
+
+ __all__.extend(['__version__', 'show_config'])
+ __all__.extend(core.__all__)
+ __all__.extend(_mat.__all__)
+ __all__.extend(lib.__all__)
+ __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma'])
+
+ # Remove one of the two occurrences of `issubdtype`, which is exposed as
+ # both `numpy.core.issubdtype` and `numpy.lib.issubdtype`.
+ __all__.remove('issubdtype')
+
+ # These are exported by np.core, but are replaced by the builtins below
+ # remove them to ensure that we don't end up with `np.long == np.int_`,
+ # which would be a breaking change.
+ del long, unicode
+ __all__.remove('long')
+ __all__.remove('unicode')
+
+ # Remove things that are in the numpy.lib but not in the numpy namespace
+ # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace)
+ # that prevents adding more things to the main namespace by accident.
+ # The list below will grow until the `from .lib import *` fixme above is
+ # taken care of
+ __all__.remove('Arrayterator')
+ del Arrayterator
+
+ # These names were removed in NumPy 1.20. For at least one release,
+ # attempts to access these names in the numpy namespace will trigger
+ # a warning, and calling the function will raise an exception.
+ _financial_names = ['fv', 'ipmt', 'irr', 'mirr', 'nper', 'npv', 'pmt',
+ 'ppmt', 'pv', 'rate']
+ __expired_functions__ = {
+ name: (f'In accordance with NEP 32, the function {name} was removed '
+ 'from NumPy version 1.20. A replacement for this function '
+ 'is available in the numpy_financial library: '
+ 'https://pypi.org/project/numpy-financial')
+ for name in _financial_names}
+
+ # Filter out Cython harmless warnings
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
+ warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
+
+ # oldnumeric and numarray were removed in 1.9. In case some packages import
+ # but do not use them, we define them here for backward compatibility.
+ oldnumeric = 'removed'
+ numarray = 'removed'
+
+ def __getattr__(attr):
+ # Warn for expired attributes, and return a dummy function
+ # that always raises an exception.
+ import warnings
+ try:
+ msg = __expired_functions__[attr]
+ except KeyError:
+ pass
+ else:
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
+
+ def _expired(*args, **kwds):
+ raise RuntimeError(msg)
+
+ return _expired
+
+ # Emit warnings for deprecated attributes
+ try:
+ val, msg = __deprecated_attrs__[attr]
+ except KeyError:
+ pass
+ else:
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
+ return val
+
+ if attr in __future_scalars__:
+ # And future warnings for those that will change, but also give
+ # the AttributeError
+ warnings.warn(
+ f"In the future `np.{attr}` will be defined as the "
+ "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
+
+ if attr in __former_attrs__:
+ raise AttributeError(__former_attrs__[attr])
+
+ # Importing Tester requires importing all of UnitTest which is not a
+ # cheap import Since it is mainly used in test suits, we lazy import it
+ # here to save on the order of 10 ms of import time for most users
+ #
+ # The previous way Tester was imported also had a side effect of adding
+ # the full `numpy.testing` namespace
+ if attr == 'testing':
+ import numpy.testing as testing
+ return testing
+ elif attr == 'Tester':
+ from .testing import Tester
+ return Tester
+
+ raise AttributeError("module {!r} has no attribute "
+ "{!r}".format(__name__, attr))
+
+ def __dir__():
+ public_symbols = globals().keys() | {'Tester', 'testing'}
+ public_symbols -= {
+ "core", "matrixlib",
+ }
+ return list(public_symbols)
+
+ # Pytest testing
+ from numpy._pytesttester import PytestTester
+ test = PytestTester(__name__)
+ del PytestTester
+
+ def _sanity_check():
+ """
+ Quick sanity checks for common bugs caused by environment.
+ There are some cases e.g. with wrong BLAS ABI that cause wrong
+ results under specific runtime conditions that are not necessarily
+ achieved during test suite runs, and it is useful to catch those early.
+
+ See https://github.com/numpy/numpy/issues/8577 and other
+ similar bug reports.
+
+ """
+ try:
+ x = ones(2, dtype=float32)
+ if not abs(x.dot(x) - float32(2.0)) < 1e-5:
+ raise AssertionError()
+ except AssertionError:
+ msg = ("The current Numpy installation ({!r}) fails to "
+ "pass simple sanity checks. This can be caused for example "
+ "by incorrect BLAS library being linked in, or by mixing "
+ "package managers (pip, conda, apt, ...). Search closed "
+ "numpy issues for similar problems.")
+ raise RuntimeError(msg.format(__file__)) from None
+
+ _sanity_check()
+ del _sanity_check
+
+ def _mac_os_check():
+ """
+ Quick Sanity check for Mac OS look for accelerate build bugs.
+ Testing numpy polyfit calls init_dgelsd(LAPACK)
+ """
+ try:
+ c = array([3., 2., 1.])
+ x = linspace(0, 2, 5)
+ y = polyval(c, x)
+ _ = polyfit(x, y, 2, cov=True)
+ except ValueError:
+ pass
+
+ if sys.platform == "darwin":
+ with warnings.catch_warnings(record=True) as w:
+ _mac_os_check()
+ # Throw runtime error, if the test failed Check for warning and error_message
+ error_message = ""
+ if len(w) > 0:
+ error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message))
+ msg = (
+ "Polyfit sanity test emitted a warning, most likely due "
+ "to using a buggy Accelerate backend."
+ "\nIf you compiled yourself, more information is available at:"
+ "\nhttps://numpy.org/doc/stable/user/building.html#accelerated-blas-lapack-libraries"
+ "\nOtherwise report this to the vendor "
+ "that provided NumPy.\n{}\n".format(error_message))
+ raise RuntimeError(msg)
+ del _mac_os_check
+
+ # We usually use madvise hugepages support, but on some old kernels it
+ # is slow and thus better avoided.
+ # Specifically kernel version 4.6 had a bug fix which probably fixed this:
+ # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
+ import os
+ use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
+ if sys.platform == "linux" and use_hugepage is None:
+ # If there is an issue with parsing the kernel version,
+ # set use_hugepages to 0. Usage of LooseVersion will handle
+ # the kernel version parsing better, but avoided since it
+ # will increase the import time. See: #16679 for related discussion.
+ try:
+ use_hugepage = 1
+ kernel_version = os.uname().release.split(".")[:2]
+ kernel_version = tuple(int(v) for v in kernel_version)
+ if kernel_version < (4, 6):
+ use_hugepage = 0
+ except ValueError:
+ use_hugepages = 0
+ elif use_hugepage is None:
+ # This is not Linux, so it should not matter, just enable anyway
+ use_hugepage = 1
+ else:
+ use_hugepage = int(use_hugepage)
+
+ # Note that this will currently only make a difference on Linux
+ core.multiarray._set_madvise_hugepage(use_hugepage)
+
+ # Give a warning if NumPy is reloaded or imported on a sub-interpreter
+ # We do this from python, since the C-module may not be reloaded and
+ # it is tidier organized.
+ core.multiarray._multiarray_umath._reload_guard()
+
+ core._set_promotion_state(os.environ.get("NPY_PROMOTION_STATE", "legacy"))
+
+ # Tell PyInstaller where to find hook-numpy.py
+ def _pyinstaller_hooks_dir():
+ from pathlib import Path
+ return [str(Path(__file__).with_name("_pyinstaller").resolve())]
+
+ # Remove symbols imported for internal use
+ del os
+
+
+# get the version using versioneer
+from .version import __version__, git_revision as __git_version__
+
+# Remove symbols imported for internal use
+del sys, warnings
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pyi b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..99a96f96ec1b9897d4158e981233bda49ad67507
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/__init__.pyi
@@ -0,0 +1,4416 @@
+import builtins
+import os
+import sys
+import mmap
+import ctypes as ct
+import array as _array
+import datetime as dt
+import enum
+from abc import abstractmethod
+from types import TracebackType, MappingProxyType
+from contextlib import ContextDecorator
+from contextlib import contextmanager
+
+if sys.version_info >= (3, 9):
+ from types import GenericAlias
+
+from numpy._pytesttester import PytestTester
+from numpy.core._internal import _ctypes
+
+from numpy._typing import (
+ # Arrays
+ ArrayLike,
+ NDArray,
+ _SupportsArray,
+ _NestedSequence,
+ _FiniteNestedSequence,
+ _SupportsArray,
+ _ArrayLikeBool_co,
+ _ArrayLikeUInt_co,
+ _ArrayLikeInt_co,
+ _ArrayLikeFloat_co,
+ _ArrayLikeComplex_co,
+ _ArrayLikeNumber_co,
+ _ArrayLikeTD64_co,
+ _ArrayLikeDT64_co,
+ _ArrayLikeObject_co,
+ _ArrayLikeStr_co,
+ _ArrayLikeBytes_co,
+ _ArrayLikeUnknown,
+ _UnknownType,
+
+ # DTypes
+ DTypeLike,
+ _DTypeLike,
+ _DTypeLikeVoid,
+ _SupportsDType,
+ _VoidDTypeLike,
+
+ # Shapes
+ _Shape,
+ _ShapeLike,
+
+ # Scalars
+ _CharLike_co,
+ _BoolLike_co,
+ _IntLike_co,
+ _FloatLike_co,
+ _ComplexLike_co,
+ _TD64Like_co,
+ _NumberLike_co,
+ _ScalarLike_co,
+
+ # `number` precision
+ NBitBase,
+ _256Bit,
+ _128Bit,
+ _96Bit,
+ _80Bit,
+ _64Bit,
+ _32Bit,
+ _16Bit,
+ _8Bit,
+ _NBitByte,
+ _NBitShort,
+ _NBitIntC,
+ _NBitIntP,
+ _NBitInt,
+ _NBitLongLong,
+ _NBitHalf,
+ _NBitSingle,
+ _NBitDouble,
+ _NBitLongDouble,
+
+ # Character codes
+ _BoolCodes,
+ _UInt8Codes,
+ _UInt16Codes,
+ _UInt32Codes,
+ _UInt64Codes,
+ _Int8Codes,
+ _Int16Codes,
+ _Int32Codes,
+ _Int64Codes,
+ _Float16Codes,
+ _Float32Codes,
+ _Float64Codes,
+ _Complex64Codes,
+ _Complex128Codes,
+ _ByteCodes,
+ _ShortCodes,
+ _IntCCodes,
+ _IntPCodes,
+ _IntCodes,
+ _LongLongCodes,
+ _UByteCodes,
+ _UShortCodes,
+ _UIntCCodes,
+ _UIntPCodes,
+ _UIntCodes,
+ _ULongLongCodes,
+ _HalfCodes,
+ _SingleCodes,
+ _DoubleCodes,
+ _LongDoubleCodes,
+ _CSingleCodes,
+ _CDoubleCodes,
+ _CLongDoubleCodes,
+ _DT64Codes,
+ _TD64Codes,
+ _StrCodes,
+ _BytesCodes,
+ _VoidCodes,
+ _ObjectCodes,
+
+ # Ufuncs
+ _UFunc_Nin1_Nout1,
+ _UFunc_Nin2_Nout1,
+ _UFunc_Nin1_Nout2,
+ _UFunc_Nin2_Nout2,
+ _GUFunc_Nin2_Nout1,
+)
+
+from numpy._typing._callable import (
+ _BoolOp,
+ _BoolBitOp,
+ _BoolSub,
+ _BoolTrueDiv,
+ _BoolMod,
+ _BoolDivMod,
+ _TD64Div,
+ _IntTrueDiv,
+ _UnsignedIntOp,
+ _UnsignedIntBitOp,
+ _UnsignedIntMod,
+ _UnsignedIntDivMod,
+ _SignedIntOp,
+ _SignedIntBitOp,
+ _SignedIntMod,
+ _SignedIntDivMod,
+ _FloatOp,
+ _FloatMod,
+ _FloatDivMod,
+ _ComplexOp,
+ _NumberOp,
+ _ComparisonOp,
+)
+
+# NOTE: Numpy's mypy plugin is used for removing the types unavailable
+# to the specific platform
+from numpy._typing._extended_precision import (
+ uint128 as uint128,
+ uint256 as uint256,
+ int128 as int128,
+ int256 as int256,
+ float80 as float80,
+ float96 as float96,
+ float128 as float128,
+ float256 as float256,
+ complex160 as complex160,
+ complex192 as complex192,
+ complex256 as complex256,
+ complex512 as complex512,
+)
+
+from collections.abc import (
+ Callable,
+ Container,
+ Iterable,
+ Iterator,
+ Mapping,
+ Sequence,
+ Sized,
+)
+from typing import (
+ Literal as L,
+ Any,
+ Generator,
+ Generic,
+ IO,
+ NoReturn,
+ overload,
+ SupportsComplex,
+ SupportsFloat,
+ SupportsInt,
+ TypeVar,
+ Union,
+ Protocol,
+ SupportsIndex,
+ Final,
+ final,
+ ClassVar,
+)
+
+# Ensures that the stubs are picked up
+from numpy import (
+ ctypeslib as ctypeslib,
+ fft as fft,
+ lib as lib,
+ linalg as linalg,
+ ma as ma,
+ polynomial as polynomial,
+ random as random,
+ testing as testing,
+ version as version,
+)
+
+from numpy.core import defchararray, records
+char = defchararray
+rec = records
+
+from numpy.core.function_base import (
+ linspace as linspace,
+ logspace as logspace,
+ geomspace as geomspace,
+)
+
+from numpy.core.fromnumeric import (
+ take as take,
+ reshape as reshape,
+ choose as choose,
+ repeat as repeat,
+ put as put,
+ swapaxes as swapaxes,
+ transpose as transpose,
+ partition as partition,
+ argpartition as argpartition,
+ sort as sort,
+ argsort as argsort,
+ argmax as argmax,
+ argmin as argmin,
+ searchsorted as searchsorted,
+ resize as resize,
+ squeeze as squeeze,
+ diagonal as diagonal,
+ trace as trace,
+ ravel as ravel,
+ nonzero as nonzero,
+ shape as shape,
+ compress as compress,
+ clip as clip,
+ sum as sum,
+ all as all,
+ any as any,
+ cumsum as cumsum,
+ ptp as ptp,
+ amax as amax,
+ amin as amin,
+ prod as prod,
+ cumprod as cumprod,
+ ndim as ndim,
+ size as size,
+ around as around,
+ mean as mean,
+ std as std,
+ var as var,
+)
+
+from numpy.core._asarray import (
+ require as require,
+)
+
+from numpy.core._type_aliases import (
+ sctypes as sctypes,
+ sctypeDict as sctypeDict,
+)
+
+from numpy.core._ufunc_config import (
+ seterr as seterr,
+ geterr as geterr,
+ setbufsize as setbufsize,
+ getbufsize as getbufsize,
+ seterrcall as seterrcall,
+ geterrcall as geterrcall,
+ _ErrKind,
+ _ErrFunc,
+ _ErrDictOptional,
+)
+
+from numpy.core.arrayprint import (
+ set_printoptions as set_printoptions,
+ get_printoptions as get_printoptions,
+ array2string as array2string,
+ format_float_scientific as format_float_scientific,
+ format_float_positional as format_float_positional,
+ array_repr as array_repr,
+ array_str as array_str,
+ set_string_function as set_string_function,
+ printoptions as printoptions,
+)
+
+from numpy.core.einsumfunc import (
+ einsum as einsum,
+ einsum_path as einsum_path,
+)
+
+from numpy.core.multiarray import (
+ ALLOW_THREADS as ALLOW_THREADS,
+ BUFSIZE as BUFSIZE,
+ CLIP as CLIP,
+ MAXDIMS as MAXDIMS,
+ MAY_SHARE_BOUNDS as MAY_SHARE_BOUNDS,
+ MAY_SHARE_EXACT as MAY_SHARE_EXACT,
+ RAISE as RAISE,
+ WRAP as WRAP,
+ tracemalloc_domain as tracemalloc_domain,
+ array as array,
+ empty_like as empty_like,
+ empty as empty,
+ zeros as zeros,
+ concatenate as concatenate,
+ inner as inner,
+ where as where,
+ lexsort as lexsort,
+ can_cast as can_cast,
+ min_scalar_type as min_scalar_type,
+ result_type as result_type,
+ dot as dot,
+ vdot as vdot,
+ bincount as bincount,
+ copyto as copyto,
+ putmask as putmask,
+ packbits as packbits,
+ unpackbits as unpackbits,
+ shares_memory as shares_memory,
+ may_share_memory as may_share_memory,
+ asarray as asarray,
+ asanyarray as asanyarray,
+ ascontiguousarray as ascontiguousarray,
+ asfortranarray as asfortranarray,
+ arange as arange,
+ busday_count as busday_count,
+ busday_offset as busday_offset,
+ compare_chararrays as compare_chararrays,
+ datetime_as_string as datetime_as_string,
+ datetime_data as datetime_data,
+ frombuffer as frombuffer,
+ fromfile as fromfile,
+ fromiter as fromiter,
+ is_busday as is_busday,
+ promote_types as promote_types,
+ seterrobj as seterrobj,
+ geterrobj as geterrobj,
+ fromstring as fromstring,
+ frompyfunc as frompyfunc,
+ nested_iters as nested_iters,
+ flagsobj,
+)
+
+from numpy.core.numeric import (
+ zeros_like as zeros_like,
+ ones as ones,
+ ones_like as ones_like,
+ full as full,
+ full_like as full_like,
+ count_nonzero as count_nonzero,
+ isfortran as isfortran,
+ argwhere as argwhere,
+ flatnonzero as flatnonzero,
+ correlate as correlate,
+ convolve as convolve,
+ outer as outer,
+ tensordot as tensordot,
+ roll as roll,
+ rollaxis as rollaxis,
+ moveaxis as moveaxis,
+ cross as cross,
+ indices as indices,
+ fromfunction as fromfunction,
+ isscalar as isscalar,
+ binary_repr as binary_repr,
+ base_repr as base_repr,
+ identity as identity,
+ allclose as allclose,
+ isclose as isclose,
+ array_equal as array_equal,
+ array_equiv as array_equiv,
+)
+
+from numpy.core.numerictypes import (
+ maximum_sctype as maximum_sctype,
+ issctype as issctype,
+ obj2sctype as obj2sctype,
+ issubclass_ as issubclass_,
+ issubsctype as issubsctype,
+ issubdtype as issubdtype,
+ sctype2char as sctype2char,
+ find_common_type as find_common_type,
+ nbytes as nbytes,
+ cast as cast,
+ ScalarType as ScalarType,
+ typecodes as typecodes,
+)
+
+from numpy.core.shape_base import (
+ atleast_1d as atleast_1d,
+ atleast_2d as atleast_2d,
+ atleast_3d as atleast_3d,
+ block as block,
+ hstack as hstack,
+ stack as stack,
+ vstack as vstack,
+)
+
+from numpy.lib import (
+ emath as emath,
+)
+
+from numpy.lib.arraypad import (
+ pad as pad,
+)
+
+from numpy.lib.arraysetops import (
+ ediff1d as ediff1d,
+ intersect1d as intersect1d,
+ setxor1d as setxor1d,
+ union1d as union1d,
+ setdiff1d as setdiff1d,
+ unique as unique,
+ in1d as in1d,
+ isin as isin,
+)
+
+from numpy.lib.arrayterator import (
+ Arrayterator as Arrayterator,
+)
+
+from numpy.lib.function_base import (
+ select as select,
+ piecewise as piecewise,
+ trim_zeros as trim_zeros,
+ copy as copy,
+ iterable as iterable,
+ percentile as percentile,
+ diff as diff,
+ gradient as gradient,
+ angle as angle,
+ unwrap as unwrap,
+ sort_complex as sort_complex,
+ disp as disp,
+ flip as flip,
+ rot90 as rot90,
+ extract as extract,
+ place as place,
+ asarray_chkfinite as asarray_chkfinite,
+ average as average,
+ bincount as bincount,
+ digitize as digitize,
+ cov as cov,
+ corrcoef as corrcoef,
+ median as median,
+ sinc as sinc,
+ hamming as hamming,
+ hanning as hanning,
+ bartlett as bartlett,
+ blackman as blackman,
+ kaiser as kaiser,
+ trapz as trapz,
+ i0 as i0,
+ add_newdoc as add_newdoc,
+ add_docstring as add_docstring,
+ meshgrid as meshgrid,
+ delete as delete,
+ insert as insert,
+ append as append,
+ interp as interp,
+ add_newdoc_ufunc as add_newdoc_ufunc,
+ quantile as quantile,
+)
+
+from numpy.lib.histograms import (
+ histogram_bin_edges as histogram_bin_edges,
+ histogram as histogram,
+ histogramdd as histogramdd,
+)
+
+from numpy.lib.index_tricks import (
+ ravel_multi_index as ravel_multi_index,
+ unravel_index as unravel_index,
+ mgrid as mgrid,
+ ogrid as ogrid,
+ r_ as r_,
+ c_ as c_,
+ s_ as s_,
+ index_exp as index_exp,
+ ix_ as ix_,
+ fill_diagonal as fill_diagonal,
+ diag_indices as diag_indices,
+ diag_indices_from as diag_indices_from,
+)
+
+from numpy.lib.nanfunctions import (
+ nansum as nansum,
+ nanmax as nanmax,
+ nanmin as nanmin,
+ nanargmax as nanargmax,
+ nanargmin as nanargmin,
+ nanmean as nanmean,
+ nanmedian as nanmedian,
+ nanpercentile as nanpercentile,
+ nanvar as nanvar,
+ nanstd as nanstd,
+ nanprod as nanprod,
+ nancumsum as nancumsum,
+ nancumprod as nancumprod,
+ nanquantile as nanquantile,
+)
+
+from numpy.lib.npyio import (
+ savetxt as savetxt,
+ loadtxt as loadtxt,
+ genfromtxt as genfromtxt,
+ recfromtxt as recfromtxt,
+ recfromcsv as recfromcsv,
+ load as load,
+ save as save,
+ savez as savez,
+ savez_compressed as savez_compressed,
+ packbits as packbits,
+ unpackbits as unpackbits,
+ fromregex as fromregex,
+)
+
+from numpy.lib.polynomial import (
+ poly as poly,
+ roots as roots,
+ polyint as polyint,
+ polyder as polyder,
+ polyadd as polyadd,
+ polysub as polysub,
+ polymul as polymul,
+ polydiv as polydiv,
+ polyval as polyval,
+ polyfit as polyfit,
+)
+
+from numpy.lib.shape_base import (
+ column_stack as column_stack,
+ row_stack as row_stack,
+ dstack as dstack,
+ array_split as array_split,
+ split as split,
+ hsplit as hsplit,
+ vsplit as vsplit,
+ dsplit as dsplit,
+ apply_over_axes as apply_over_axes,
+ expand_dims as expand_dims,
+ apply_along_axis as apply_along_axis,
+ kron as kron,
+ tile as tile,
+ get_array_wrap as get_array_wrap,
+ take_along_axis as take_along_axis,
+ put_along_axis as put_along_axis,
+)
+
+from numpy.lib.stride_tricks import (
+ broadcast_to as broadcast_to,
+ broadcast_arrays as broadcast_arrays,
+ broadcast_shapes as broadcast_shapes,
+)
+
+from numpy.lib.twodim_base import (
+ diag as diag,
+ diagflat as diagflat,
+ eye as eye,
+ fliplr as fliplr,
+ flipud as flipud,
+ tri as tri,
+ triu as triu,
+ tril as tril,
+ vander as vander,
+ histogram2d as histogram2d,
+ mask_indices as mask_indices,
+ tril_indices as tril_indices,
+ tril_indices_from as tril_indices_from,
+ triu_indices as triu_indices,
+ triu_indices_from as triu_indices_from,
+)
+
+from numpy.lib.type_check import (
+ mintypecode as mintypecode,
+ asfarray as asfarray,
+ real as real,
+ imag as imag,
+ iscomplex as iscomplex,
+ isreal as isreal,
+ iscomplexobj as iscomplexobj,
+ isrealobj as isrealobj,
+ nan_to_num as nan_to_num,
+ real_if_close as real_if_close,
+ typename as typename,
+ common_type as common_type,
+)
+
+from numpy.lib.ufunclike import (
+ fix as fix,
+ isposinf as isposinf,
+ isneginf as isneginf,
+)
+
+from numpy.lib.utils import (
+ issubclass_ as issubclass_,
+ issubsctype as issubsctype,
+ issubdtype as issubdtype,
+ deprecate as deprecate,
+ deprecate_with_doc as deprecate_with_doc,
+ get_include as get_include,
+ info as info,
+ source as source,
+ who as who,
+ lookfor as lookfor,
+ byte_bounds as byte_bounds,
+ safe_eval as safe_eval,
+ show_runtime as show_runtime,
+)
+
+from numpy.matrixlib import (
+ asmatrix as asmatrix,
+ mat as mat,
+ bmat as bmat,
+)
+
+_AnyStr_contra = TypeVar("_AnyStr_contra", str, bytes, contravariant=True)
+
+# Protocol for representing file-like-objects accepted
+# by `ndarray.tofile` and `fromfile`
+class _IOProtocol(Protocol):
+ def flush(self) -> object: ...
+ def fileno(self) -> int: ...
+ def tell(self) -> SupportsIndex: ...
+ def seek(self, offset: int, whence: int, /) -> object: ...
+
+# NOTE: `seek`, `write` and `flush` are technically only required
+# for `readwrite`/`write` modes
+class _MemMapIOProtocol(Protocol):
+ def flush(self) -> object: ...
+ def fileno(self) -> SupportsIndex: ...
+ def tell(self) -> int: ...
+ def seek(self, offset: int, whence: int, /) -> object: ...
+ def write(self, s: bytes, /) -> object: ...
+ @property
+ def read(self) -> object: ...
+
+class _SupportsWrite(Protocol[_AnyStr_contra]):
+ def write(self, s: _AnyStr_contra, /) -> object: ...
+
+__all__: list[str]
+__path__: list[str]
+__version__: str
+__git_version__: str
+test: PytestTester
+
+# TODO: Move placeholders to their respective module once
+# their annotations are properly implemented
+#
+# Placeholders for classes
+
+# Some of these are aliases; others are wrappers with an identical signature
+round = around
+round_ = around
+max = amax
+min = amin
+product = prod
+cumproduct = cumprod
+sometrue = any
+alltrue = all
+
+def show_config() -> None: ...
+
+_NdArraySubClass = TypeVar("_NdArraySubClass", bound=ndarray)
+_DTypeScalar_co = TypeVar("_DTypeScalar_co", covariant=True, bound=generic)
+_ByteOrder = L["S", "<", ">", "=", "|", "L", "B", "N", "I"]
+
+@final
+class dtype(Generic[_DTypeScalar_co]):
+ names: None | tuple[builtins.str, ...]
+ # Overload for subclass of generic
+ @overload
+ def __new__(
+ cls,
+ dtype: type[_DTypeScalar_co],
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[_DTypeScalar_co]: ...
+ # Overloads for string aliases, Python types, and some assorted
+ # other special cases. Order is sometimes important because of the
+ # subtype relationships
+ #
+ # bool < int < float < complex < object
+ #
+ # so we have to make sure the overloads for the narrowest type is
+ # first.
+ # Builtin types
+ @overload
+ def __new__(cls, dtype: type[bool], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[bool_]: ...
+ @overload
+ def __new__(cls, dtype: type[int], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int_]: ...
+ @overload
+ def __new__(cls, dtype: None | type[float], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[float_]: ...
+ @overload
+ def __new__(cls, dtype: type[complex], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[complex_]: ...
+ @overload
+ def __new__(cls, dtype: type[builtins.str], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[str_]: ...
+ @overload
+ def __new__(cls, dtype: type[bytes], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[bytes_]: ...
+
+ # `unsignedinteger` string-based representations and ctypes
+ @overload
+ def __new__(cls, dtype: _UInt8Codes | type[ct.c_uint8], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uint8]: ...
+ @overload
+ def __new__(cls, dtype: _UInt16Codes | type[ct.c_uint16], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uint16]: ...
+ @overload
+ def __new__(cls, dtype: _UInt32Codes | type[ct.c_uint32], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uint32]: ...
+ @overload
+ def __new__(cls, dtype: _UInt64Codes | type[ct.c_uint64], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uint64]: ...
+ @overload
+ def __new__(cls, dtype: _UByteCodes | type[ct.c_ubyte], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[ubyte]: ...
+ @overload
+ def __new__(cls, dtype: _UShortCodes | type[ct.c_ushort], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[ushort]: ...
+ @overload
+ def __new__(cls, dtype: _UIntCCodes | type[ct.c_uint], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uintc]: ...
+
+ # NOTE: We're assuming here that `uint_ptr_t == size_t`,
+ # an assumption that does not hold in rare cases (same for `ssize_t`)
+ @overload
+ def __new__(cls, dtype: _UIntPCodes | type[ct.c_void_p] | type[ct.c_size_t], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uintp]: ...
+ @overload
+ def __new__(cls, dtype: _UIntCodes | type[ct.c_ulong], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[uint]: ...
+ @overload
+ def __new__(cls, dtype: _ULongLongCodes | type[ct.c_ulonglong], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[ulonglong]: ...
+
+ # `signedinteger` string-based representations and ctypes
+ @overload
+ def __new__(cls, dtype: _Int8Codes | type[ct.c_int8], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int8]: ...
+ @overload
+ def __new__(cls, dtype: _Int16Codes | type[ct.c_int16], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int16]: ...
+ @overload
+ def __new__(cls, dtype: _Int32Codes | type[ct.c_int32], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int32]: ...
+ @overload
+ def __new__(cls, dtype: _Int64Codes | type[ct.c_int64], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int64]: ...
+ @overload
+ def __new__(cls, dtype: _ByteCodes | type[ct.c_byte], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[byte]: ...
+ @overload
+ def __new__(cls, dtype: _ShortCodes | type[ct.c_short], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[short]: ...
+ @overload
+ def __new__(cls, dtype: _IntCCodes | type[ct.c_int], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[intc]: ...
+ @overload
+ def __new__(cls, dtype: _IntPCodes | type[ct.c_ssize_t], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[intp]: ...
+ @overload
+ def __new__(cls, dtype: _IntCodes | type[ct.c_long], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[int_]: ...
+ @overload
+ def __new__(cls, dtype: _LongLongCodes | type[ct.c_longlong], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[longlong]: ...
+
+ # `floating` string-based representations and ctypes
+ @overload
+ def __new__(cls, dtype: _Float16Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[float16]: ...
+ @overload
+ def __new__(cls, dtype: _Float32Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[float32]: ...
+ @overload
+ def __new__(cls, dtype: _Float64Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[float64]: ...
+ @overload
+ def __new__(cls, dtype: _HalfCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[half]: ...
+ @overload
+ def __new__(cls, dtype: _SingleCodes | type[ct.c_float], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[single]: ...
+ @overload
+ def __new__(cls, dtype: _DoubleCodes | type[ct.c_double], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[double]: ...
+ @overload
+ def __new__(cls, dtype: _LongDoubleCodes | type[ct.c_longdouble], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[longdouble]: ...
+
+ # `complexfloating` string-based representations
+ @overload
+ def __new__(cls, dtype: _Complex64Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[complex64]: ...
+ @overload
+ def __new__(cls, dtype: _Complex128Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[complex128]: ...
+ @overload
+ def __new__(cls, dtype: _CSingleCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[csingle]: ...
+ @overload
+ def __new__(cls, dtype: _CDoubleCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[cdouble]: ...
+ @overload
+ def __new__(cls, dtype: _CLongDoubleCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[clongdouble]: ...
+
+ # Miscellaneous string-based representations and ctypes
+ @overload
+ def __new__(cls, dtype: _BoolCodes | type[ct.c_bool], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[bool_]: ...
+ @overload
+ def __new__(cls, dtype: _TD64Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[timedelta64]: ...
+ @overload
+ def __new__(cls, dtype: _DT64Codes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[datetime64]: ...
+ @overload
+ def __new__(cls, dtype: _StrCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[str_]: ...
+ @overload
+ def __new__(cls, dtype: _BytesCodes | type[ct.c_char], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[bytes_]: ...
+ @overload
+ def __new__(cls, dtype: _VoidCodes, align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[void]: ...
+ @overload
+ def __new__(cls, dtype: _ObjectCodes | type[ct.py_object[Any]], align: bool = ..., copy: bool = ..., metadata: dict[builtins.str, Any] = ...) -> dtype[object_]: ...
+
+ # dtype of a dtype is the same dtype
+ @overload
+ def __new__(
+ cls,
+ dtype: dtype[_DTypeScalar_co],
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[_DTypeScalar_co]: ...
+ @overload
+ def __new__(
+ cls,
+ dtype: _SupportsDType[dtype[_DTypeScalar_co]],
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[_DTypeScalar_co]: ...
+ # Handle strings that can't be expressed as literals; i.e. s1, s2, ...
+ @overload
+ def __new__(
+ cls,
+ dtype: builtins.str,
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[Any]: ...
+ # Catchall overload for void-likes
+ @overload
+ def __new__(
+ cls,
+ dtype: _VoidDTypeLike,
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[void]: ...
+ # Catchall overload for object-likes
+ @overload
+ def __new__(
+ cls,
+ dtype: type[object],
+ align: bool = ...,
+ copy: bool = ...,
+ metadata: dict[builtins.str, Any] = ...,
+ ) -> dtype[object_]: ...
+
+ if sys.version_info >= (3, 9):
+ def __class_getitem__(self, item: Any) -> GenericAlias: ...
+
+ @overload
+ def __getitem__(self: dtype[void], key: list[builtins.str]) -> dtype[void]: ...
+ @overload
+ def __getitem__(self: dtype[void], key: builtins.str | SupportsIndex) -> dtype[Any]: ...
+
+ # NOTE: In the future 1-based multiplications will also yield `flexible` dtypes
+ @overload
+ def __mul__(self: _DType, value: L[1]) -> _DType: ...
+ @overload
+ def __mul__(self: _FlexDType, value: SupportsIndex) -> _FlexDType: ...
+ @overload
+ def __mul__(self, value: SupportsIndex) -> dtype[void]: ...
+
+ # NOTE: `__rmul__` seems to be broken when used in combination with
+ # literals as of mypy 0.902. Set the return-type to `dtype[Any]` for
+ # now for non-flexible dtypes.
+ @overload
+ def __rmul__(self: _FlexDType, value: SupportsIndex) -> _FlexDType: ...
+ @overload
+ def __rmul__(self, value: SupportsIndex) -> dtype[Any]: ...
+
+ def __gt__(self, other: DTypeLike) -> bool: ...
+ def __ge__(self, other: DTypeLike) -> bool: ...
+ def __lt__(self, other: DTypeLike) -> bool: ...
+ def __le__(self, other: DTypeLike) -> bool: ...
+
+ # Explicitly defined `__eq__` and `__ne__` to get around mypy's
+ # `strict_equality` option; even though their signatures are
+ # identical to their `object`-based counterpart
+ def __eq__(self, other: Any) -> bool: ...
+ def __ne__(self, other: Any) -> bool: ...
+
+ @property
+ def alignment(self) -> int: ...
+ @property
+ def base(self) -> dtype[Any]: ...
+ @property
+ def byteorder(self) -> builtins.str: ...
+ @property
+ def char(self) -> builtins.str: ...
+ @property
+ def descr(self) -> list[tuple[builtins.str, builtins.str] | tuple[builtins.str, builtins.str, _Shape]]: ...
+ @property
+ def fields(
+ self,
+ ) -> None | MappingProxyType[builtins.str, tuple[dtype[Any], int] | tuple[dtype[Any], int, Any]]: ...
+ @property
+ def flags(self) -> int: ...
+ @property
+ def hasobject(self) -> bool: ...
+ @property
+ def isbuiltin(self) -> int: ...
+ @property
+ def isnative(self) -> bool: ...
+ @property
+ def isalignedstruct(self) -> bool: ...
+ @property
+ def itemsize(self) -> int: ...
+ @property
+ def kind(self) -> builtins.str: ...
+ @property
+ def metadata(self) -> None | MappingProxyType[builtins.str, Any]: ...
+ @property
+ def name(self) -> builtins.str: ...
+ @property
+ def num(self) -> int: ...
+ @property
+ def shape(self) -> _Shape: ...
+ @property
+ def ndim(self) -> int: ...
+ @property
+ def subdtype(self) -> None | tuple[dtype[Any], _Shape]: ...
+ def newbyteorder(self: _DType, __new_order: _ByteOrder = ...) -> _DType: ...
+ @property
+ def str(self) -> builtins.str: ...
+ @property
+ def type(self) -> type[_DTypeScalar_co]: ...
+
+_ArrayLikeInt = Union[
+ int,
+ integer,
+ Sequence[Union[int, integer]],
+ Sequence[Sequence[Any]], # TODO: wait for support for recursive types
+ ndarray
+]
+
+_FlatIterSelf = TypeVar("_FlatIterSelf", bound=flatiter)
+
+@final
+class flatiter(Generic[_NdArraySubClass]):
+ __hash__: ClassVar[None]
+ @property
+ def base(self) -> _NdArraySubClass: ...
+ @property
+ def coords(self) -> _Shape: ...
+ @property
+ def index(self) -> int: ...
+ def copy(self) -> _NdArraySubClass: ...
+ def __iter__(self: _FlatIterSelf) -> _FlatIterSelf: ...
+ def __next__(self: flatiter[ndarray[Any, dtype[_ScalarType]]]) -> _ScalarType: ...
+ def __len__(self) -> int: ...
+ @overload
+ def __getitem__(
+ self: flatiter[ndarray[Any, dtype[_ScalarType]]],
+ key: int | integer | tuple[int | integer],
+ ) -> _ScalarType: ...
+ @overload
+ def __getitem__(
+ self,
+ key: _ArrayLikeInt | slice | ellipsis | tuple[_ArrayLikeInt | slice | ellipsis],
+ ) -> _NdArraySubClass: ...
+ # TODO: `__setitem__` operates via `unsafe` casting rules, and can
+ # thus accept any type accepted by the relevant underlying `np.generic`
+ # constructor.
+ # This means that `value` must in reality be a supertype of `npt.ArrayLike`.
+ def __setitem__(
+ self,
+ key: _ArrayLikeInt | slice | ellipsis | tuple[_ArrayLikeInt | slice | ellipsis],
+ value: Any,
+ ) -> None: ...
+ @overload
+ def __array__(self: flatiter[ndarray[Any, _DType]], dtype: None = ..., /) -> ndarray[Any, _DType]: ...
+ @overload
+ def __array__(self, dtype: _DType, /) -> ndarray[Any, _DType]: ...
+
+_OrderKACF = L[None, "K", "A", "C", "F"]
+_OrderACF = L[None, "A", "C", "F"]
+_OrderCF = L[None, "C", "F"]
+
+_ModeKind = L["raise", "wrap", "clip"]
+_PartitionKind = L["introselect"]
+_SortKind = L["quicksort", "mergesort", "heapsort", "stable"]
+_SortSide = L["left", "right"]
+
+_ArraySelf = TypeVar("_ArraySelf", bound=_ArrayOrScalarCommon)
+
+class _ArrayOrScalarCommon:
+ @property
+ def T(self: _ArraySelf) -> _ArraySelf: ...
+ @property
+ def data(self) -> memoryview: ...
+ @property
+ def flags(self) -> flagsobj: ...
+ @property
+ def itemsize(self) -> int: ...
+ @property
+ def nbytes(self) -> int: ...
+ def __bool__(self) -> bool: ...
+ def __bytes__(self) -> bytes: ...
+ def __str__(self) -> str: ...
+ def __repr__(self) -> str: ...
+ def __copy__(self: _ArraySelf) -> _ArraySelf: ...
+ def __deepcopy__(self: _ArraySelf, memo: None | dict[int, Any], /) -> _ArraySelf: ...
+
+ # TODO: How to deal with the non-commutative nature of `==` and `!=`?
+ # xref numpy/numpy#17368
+ def __eq__(self, other: Any) -> Any: ...
+ def __ne__(self, other: Any) -> Any: ...
+ def copy(self: _ArraySelf, order: _OrderKACF = ...) -> _ArraySelf: ...
+ def dump(self, file: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _SupportsWrite[bytes]) -> None: ...
+ def dumps(self) -> bytes: ...
+ def tobytes(self, order: _OrderKACF = ...) -> bytes: ...
+ # NOTE: `tostring()` is deprecated and therefore excluded
+ # def tostring(self, order=...): ...
+ def tofile(
+ self,
+ fid: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _IOProtocol,
+ sep: str = ...,
+ format: str = ...,
+ ) -> None: ...
+ # generics and 0d arrays return builtin scalars
+ def tolist(self) -> Any: ...
+
+ @property
+ def __array_interface__(self) -> dict[str, Any]: ...
+ @property
+ def __array_priority__(self) -> float: ...
+ @property
+ def __array_struct__(self) -> Any: ... # builtins.PyCapsule
+ def __setstate__(self, state: tuple[
+ SupportsIndex, # version
+ _ShapeLike, # Shape
+ _DType_co, # DType
+ bool, # F-continuous
+ bytes | list[Any], # Data
+ ], /) -> None: ...
+ # a `bool_` is returned when `keepdims=True` and `self` is a 0d array
+
+ @overload
+ def all(
+ self,
+ axis: None = ...,
+ out: None = ...,
+ keepdims: L[False] = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> bool_: ...
+ @overload
+ def all(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def all(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def any(
+ self,
+ axis: None = ...,
+ out: None = ...,
+ keepdims: L[False] = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> bool_: ...
+ @overload
+ def any(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def any(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def argmax(
+ self,
+ axis: None = ...,
+ out: None = ...,
+ *,
+ keepdims: L[False] = ...,
+ ) -> intp: ...
+ @overload
+ def argmax(
+ self,
+ axis: SupportsIndex = ...,
+ out: None = ...,
+ *,
+ keepdims: bool = ...,
+ ) -> Any: ...
+ @overload
+ def argmax(
+ self,
+ axis: None | SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ *,
+ keepdims: bool = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def argmin(
+ self,
+ axis: None = ...,
+ out: None = ...,
+ *,
+ keepdims: L[False] = ...,
+ ) -> intp: ...
+ @overload
+ def argmin(
+ self,
+ axis: SupportsIndex = ...,
+ out: None = ...,
+ *,
+ keepdims: bool = ...,
+ ) -> Any: ...
+ @overload
+ def argmin(
+ self,
+ axis: None | SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ *,
+ keepdims: bool = ...,
+ ) -> _NdArraySubClass: ...
+
+ def argsort(
+ self,
+ axis: None | SupportsIndex = ...,
+ kind: None | _SortKind = ...,
+ order: None | str | Sequence[str] = ...,
+ ) -> ndarray: ...
+
+ @overload
+ def choose(
+ self,
+ choices: ArrayLike,
+ out: None = ...,
+ mode: _ModeKind = ...,
+ ) -> ndarray: ...
+ @overload
+ def choose(
+ self,
+ choices: ArrayLike,
+ out: _NdArraySubClass = ...,
+ mode: _ModeKind = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def clip(
+ self,
+ min: ArrayLike = ...,
+ max: None | ArrayLike = ...,
+ out: None = ...,
+ **kwargs: Any,
+ ) -> ndarray: ...
+ @overload
+ def clip(
+ self,
+ min: None = ...,
+ max: ArrayLike = ...,
+ out: None = ...,
+ **kwargs: Any,
+ ) -> ndarray: ...
+ @overload
+ def clip(
+ self,
+ min: ArrayLike = ...,
+ max: None | ArrayLike = ...,
+ out: _NdArraySubClass = ...,
+ **kwargs: Any,
+ ) -> _NdArraySubClass: ...
+ @overload
+ def clip(
+ self,
+ min: None = ...,
+ max: ArrayLike = ...,
+ out: _NdArraySubClass = ...,
+ **kwargs: Any,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def compress(
+ self,
+ a: ArrayLike,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ ) -> ndarray: ...
+ @overload
+ def compress(
+ self,
+ a: ArrayLike,
+ axis: None | SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ ) -> _NdArraySubClass: ...
+
+ def conj(self: _ArraySelf) -> _ArraySelf: ...
+
+ def conjugate(self: _ArraySelf) -> _ArraySelf: ...
+
+ @overload
+ def cumprod(
+ self,
+ axis: None | SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ) -> ndarray: ...
+ @overload
+ def cumprod(
+ self,
+ axis: None | SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def cumsum(
+ self,
+ axis: None | SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ) -> ndarray: ...
+ @overload
+ def cumsum(
+ self,
+ axis: None | SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def max(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def max(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def mean(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def mean(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def min(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def min(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ def newbyteorder(
+ self: _ArraySelf,
+ __new_order: _ByteOrder = ...,
+ ) -> _ArraySelf: ...
+
+ @overload
+ def prod(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def prod(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def ptp(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ ) -> Any: ...
+ @overload
+ def ptp(
+ self,
+ axis: None | _ShapeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def round(
+ self: _ArraySelf,
+ decimals: SupportsIndex = ...,
+ out: None = ...,
+ ) -> _ArraySelf: ...
+ @overload
+ def round(
+ self,
+ decimals: SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def std(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def std(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def sum(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def sum(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ keepdims: bool = ...,
+ initial: _NumberLike_co = ...,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def var(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> Any: ...
+ @overload
+ def var(
+ self,
+ axis: None | _ShapeLike = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ ddof: float = ...,
+ keepdims: bool = ...,
+ *,
+ where: _ArrayLikeBool_co = ...,
+ ) -> _NdArraySubClass: ...
+
+_DType = TypeVar("_DType", bound=dtype[Any])
+_DType_co = TypeVar("_DType_co", covariant=True, bound=dtype[Any])
+_FlexDType = TypeVar("_FlexDType", bound=dtype[flexible])
+
+# TODO: Set the `bound` to something more suitable once we
+# have proper shape support
+_ShapeType = TypeVar("_ShapeType", bound=Any)
+_ShapeType2 = TypeVar("_ShapeType2", bound=Any)
+_NumberType = TypeVar("_NumberType", bound=number[Any])
+
+# There is currently no exhaustive way to type the buffer protocol,
+# as it is implemented exclusively in the C API (python/typing#593)
+_SupportsBuffer = Union[
+ bytes,
+ bytearray,
+ memoryview,
+ _array.array[Any],
+ mmap.mmap,
+ NDArray[Any],
+ generic,
+]
+
+_T = TypeVar("_T")
+_T_co = TypeVar("_T_co", covariant=True)
+_T_contra = TypeVar("_T_contra", contravariant=True)
+_2Tuple = tuple[_T, _T]
+_CastingKind = L["no", "equiv", "safe", "same_kind", "unsafe"]
+
+_ArrayUInt_co = NDArray[Union[bool_, unsignedinteger[Any]]]
+_ArrayInt_co = NDArray[Union[bool_, integer[Any]]]
+_ArrayFloat_co = NDArray[Union[bool_, integer[Any], floating[Any]]]
+_ArrayComplex_co = NDArray[Union[bool_, integer[Any], floating[Any], complexfloating[Any, Any]]]
+_ArrayNumber_co = NDArray[Union[bool_, number[Any]]]
+_ArrayTD64_co = NDArray[Union[bool_, integer[Any], timedelta64]]
+
+# Introduce an alias for `dtype` to avoid naming conflicts.
+_dtype = dtype
+
+# `builtins.PyCapsule` unfortunately lacks annotations as of the moment;
+# use `Any` as a stopgap measure
+_PyCapsule = Any
+
+class _SupportsItem(Protocol[_T_co]):
+ def item(self, args: Any, /) -> _T_co: ...
+
+class _SupportsReal(Protocol[_T_co]):
+ @property
+ def real(self) -> _T_co: ...
+
+class _SupportsImag(Protocol[_T_co]):
+ @property
+ def imag(self) -> _T_co: ...
+
+class ndarray(_ArrayOrScalarCommon, Generic[_ShapeType, _DType_co]):
+ __hash__: ClassVar[None]
+ @property
+ def base(self) -> None | ndarray: ...
+ @property
+ def ndim(self) -> int: ...
+ @property
+ def size(self) -> int: ...
+ @property
+ def real(
+ self: ndarray[_ShapeType, dtype[_SupportsReal[_ScalarType]]], # type: ignore[type-var]
+ ) -> ndarray[_ShapeType, _dtype[_ScalarType]]: ...
+ @real.setter
+ def real(self, value: ArrayLike) -> None: ...
+ @property
+ def imag(
+ self: ndarray[_ShapeType, dtype[_SupportsImag[_ScalarType]]], # type: ignore[type-var]
+ ) -> ndarray[_ShapeType, _dtype[_ScalarType]]: ...
+ @imag.setter
+ def imag(self, value: ArrayLike) -> None: ...
+ def __new__(
+ cls: type[_ArraySelf],
+ shape: _ShapeLike,
+ dtype: DTypeLike = ...,
+ buffer: None | _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: None | _ShapeLike = ...,
+ order: _OrderKACF = ...,
+ ) -> _ArraySelf: ...
+
+ if sys.version_info >= (3, 9):
+ def __class_getitem__(self, item: Any) -> GenericAlias: ...
+
+ @overload
+ def __array__(self, dtype: None = ..., /) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def __array__(self, dtype: _DType, /) -> ndarray[Any, _DType]: ...
+
+ def __array_ufunc__(
+ self,
+ ufunc: ufunc,
+ method: L["__call__", "reduce", "reduceat", "accumulate", "outer", "inner"],
+ *inputs: Any,
+ **kwargs: Any,
+ ) -> Any: ...
+
+ def __array_function__(
+ self,
+ func: Callable[..., Any],
+ types: Iterable[type],
+ args: Iterable[Any],
+ kwargs: Mapping[str, Any],
+ ) -> Any: ...
+
+ # NOTE: In practice any object is accepted by `obj`, but as `__array_finalize__`
+ # is a pseudo-abstract method the type has been narrowed down in order to
+ # grant subclasses a bit more flexiblity
+ def __array_finalize__(self, obj: None | NDArray[Any], /) -> None: ...
+
+ def __array_wrap__(
+ self,
+ array: ndarray[_ShapeType2, _DType],
+ context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+ /,
+ ) -> ndarray[_ShapeType2, _DType]: ...
+
+ def __array_prepare__(
+ self,
+ array: ndarray[_ShapeType2, _DType],
+ context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+ /,
+ ) -> ndarray[_ShapeType2, _DType]: ...
+
+ @overload
+ def __getitem__(self, key: (
+ NDArray[integer[Any]]
+ | NDArray[bool_]
+ | tuple[NDArray[integer[Any]] | NDArray[bool_], ...]
+ )) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...]) -> Any: ...
+ @overload
+ def __getitem__(self, key: (
+ None
+ | slice
+ | ellipsis
+ | SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...]
+ )) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def __getitem__(self: NDArray[void], key: str) -> NDArray[Any]: ...
+ @overload
+ def __getitem__(self: NDArray[void], key: list[str]) -> ndarray[_ShapeType, _dtype[void]]: ...
+
+ @property
+ def ctypes(self) -> _ctypes[int]: ...
+ @property
+ def shape(self) -> _Shape: ...
+ @shape.setter
+ def shape(self, value: _ShapeLike) -> None: ...
+ @property
+ def strides(self) -> _Shape: ...
+ @strides.setter
+ def strides(self, value: _ShapeLike) -> None: ...
+ def byteswap(self: _ArraySelf, inplace: bool = ...) -> _ArraySelf: ...
+ def fill(self, value: Any) -> None: ...
+ @property
+ def flat(self: _NdArraySubClass) -> flatiter[_NdArraySubClass]: ...
+
+ # Use the same output type as that of the underlying `generic`
+ @overload
+ def item(
+ self: ndarray[Any, _dtype[_SupportsItem[_T]]], # type: ignore[type-var]
+ *args: SupportsIndex,
+ ) -> _T: ...
+ @overload
+ def item(
+ self: ndarray[Any, _dtype[_SupportsItem[_T]]], # type: ignore[type-var]
+ args: tuple[SupportsIndex, ...],
+ /,
+ ) -> _T: ...
+
+ @overload
+ def itemset(self, value: Any, /) -> None: ...
+ @overload
+ def itemset(self, item: _ShapeLike, value: Any, /) -> None: ...
+
+ @overload
+ def resize(self, new_shape: _ShapeLike, /, *, refcheck: bool = ...) -> None: ...
+ @overload
+ def resize(self, *new_shape: SupportsIndex, refcheck: bool = ...) -> None: ...
+
+ def setflags(
+ self, write: bool = ..., align: bool = ..., uic: bool = ...
+ ) -> None: ...
+
+ def squeeze(
+ self,
+ axis: None | SupportsIndex | tuple[SupportsIndex, ...] = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ def swapaxes(
+ self,
+ axis1: SupportsIndex,
+ axis2: SupportsIndex,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ @overload
+ def transpose(self: _ArraySelf, axes: None | _ShapeLike, /) -> _ArraySelf: ...
+ @overload
+ def transpose(self: _ArraySelf, *axes: SupportsIndex) -> _ArraySelf: ...
+
+ def argpartition(
+ self,
+ kth: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ kind: _PartitionKind = ...,
+ order: None | str | Sequence[str] = ...,
+ ) -> ndarray[Any, _dtype[intp]]: ...
+
+ def diagonal(
+ self,
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ # 1D + 1D returns a scalar;
+ # all other with at least 1 non-0D array return an ndarray.
+ @overload
+ def dot(self, b: _ScalarLike_co, out: None = ...) -> ndarray: ...
+ @overload
+ def dot(self, b: ArrayLike, out: None = ...) -> Any: ... # type: ignore[misc]
+ @overload
+ def dot(self, b: ArrayLike, out: _NdArraySubClass) -> _NdArraySubClass: ...
+
+ # `nonzero()` is deprecated for 0d arrays/generics
+ def nonzero(self) -> tuple[ndarray[Any, _dtype[intp]], ...]: ...
+
+ def partition(
+ self,
+ kth: _ArrayLikeInt_co,
+ axis: SupportsIndex = ...,
+ kind: _PartitionKind = ...,
+ order: None | str | Sequence[str] = ...,
+ ) -> None: ...
+
+ # `put` is technically available to `generic`,
+ # but is pointless as `generic`s are immutable
+ def put(
+ self,
+ ind: _ArrayLikeInt_co,
+ v: ArrayLike,
+ mode: _ModeKind = ...,
+ ) -> None: ...
+
+ @overload
+ def searchsorted( # type: ignore[misc]
+ self, # >= 1D array
+ v: _ScalarLike_co, # 0D array-like
+ side: _SortSide = ...,
+ sorter: None | _ArrayLikeInt_co = ...,
+ ) -> intp: ...
+ @overload
+ def searchsorted(
+ self, # >= 1D array
+ v: ArrayLike,
+ side: _SortSide = ...,
+ sorter: None | _ArrayLikeInt_co = ...,
+ ) -> ndarray[Any, _dtype[intp]]: ...
+
+ def setfield(
+ self,
+ val: ArrayLike,
+ dtype: DTypeLike,
+ offset: SupportsIndex = ...,
+ ) -> None: ...
+
+ def sort(
+ self,
+ axis: SupportsIndex = ...,
+ kind: None | _SortKind = ...,
+ order: None | str | Sequence[str] = ...,
+ ) -> None: ...
+
+ @overload
+ def trace(
+ self, # >= 2D array
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: None = ...,
+ ) -> Any: ...
+ @overload
+ def trace(
+ self, # >= 2D array
+ offset: SupportsIndex = ...,
+ axis1: SupportsIndex = ...,
+ axis2: SupportsIndex = ...,
+ dtype: DTypeLike = ...,
+ out: _NdArraySubClass = ...,
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def take( # type: ignore[misc]
+ self: ndarray[Any, _dtype[_ScalarType]],
+ indices: _IntLike_co,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+ ) -> _ScalarType: ...
+ @overload
+ def take( # type: ignore[misc]
+ self,
+ indices: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def take(
+ self,
+ indices: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ mode: _ModeKind = ...,
+ ) -> _NdArraySubClass: ...
+
+ def repeat(
+ self,
+ repeats: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ def flatten(
+ self,
+ order: _OrderKACF = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ def ravel(
+ self,
+ order: _OrderKACF = ...,
+ ) -> ndarray[Any, _DType_co]: ...
+
+ @overload
+ def reshape(
+ self, shape: _ShapeLike, /, *, order: _OrderACF = ...
+ ) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def reshape(
+ self, *shape: SupportsIndex, order: _OrderACF = ...
+ ) -> ndarray[Any, _DType_co]: ...
+
+ @overload
+ def astype(
+ self,
+ dtype: _DTypeLike[_ScalarType],
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ subok: bool = ...,
+ copy: bool | _CopyMode = ...,
+ ) -> NDArray[_ScalarType]: ...
+ @overload
+ def astype(
+ self,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ subok: bool = ...,
+ copy: bool | _CopyMode = ...,
+ ) -> NDArray[Any]: ...
+
+ @overload
+ def view(self: _ArraySelf) -> _ArraySelf: ...
+ @overload
+ def view(self, type: type[_NdArraySubClass]) -> _NdArraySubClass: ...
+ @overload
+ def view(self, dtype: _DTypeLike[_ScalarType]) -> NDArray[_ScalarType]: ...
+ @overload
+ def view(self, dtype: DTypeLike) -> NDArray[Any]: ...
+ @overload
+ def view(
+ self,
+ dtype: DTypeLike,
+ type: type[_NdArraySubClass],
+ ) -> _NdArraySubClass: ...
+
+ @overload
+ def getfield(
+ self,
+ dtype: _DTypeLike[_ScalarType],
+ offset: SupportsIndex = ...
+ ) -> NDArray[_ScalarType]: ...
+ @overload
+ def getfield(
+ self,
+ dtype: DTypeLike,
+ offset: SupportsIndex = ...
+ ) -> NDArray[Any]: ...
+
+ # Dispatch to the underlying `generic` via protocols
+ def __int__(
+ self: ndarray[Any, _dtype[SupportsInt]], # type: ignore[type-var]
+ ) -> int: ...
+
+ def __float__(
+ self: ndarray[Any, _dtype[SupportsFloat]], # type: ignore[type-var]
+ ) -> float: ...
+
+ def __complex__(
+ self: ndarray[Any, _dtype[SupportsComplex]], # type: ignore[type-var]
+ ) -> complex: ...
+
+ def __index__(
+ self: ndarray[Any, _dtype[SupportsIndex]], # type: ignore[type-var]
+ ) -> int: ...
+
+ def __len__(self) -> int: ...
+ def __setitem__(self, key, value): ...
+ def __iter__(self) -> Any: ...
+ def __contains__(self, key) -> bool: ...
+
+ # The last overload is for catching recursive objects whose
+ # nesting is too deep.
+ # The first overload is for catching `bytes` (as they are a subtype of
+ # `Sequence[int]`) and `str`. As `str` is a recursive sequence of
+ # strings, it will pass through the final overload otherwise
+
+ @overload
+ def __lt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co) -> NDArray[bool_]: ...
+ @overload
+ def __lt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[bool_]: ...
+ @overload
+ def __lt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[bool_]: ...
+ @overload
+ def __lt__(self: NDArray[object_], other: Any) -> NDArray[bool_]: ...
+ @overload
+ def __lt__(self: NDArray[Any], other: _ArrayLikeObject_co) -> NDArray[bool_]: ...
+
+ @overload
+ def __le__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co) -> NDArray[bool_]: ...
+ @overload
+ def __le__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[bool_]: ...
+ @overload
+ def __le__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[bool_]: ...
+ @overload
+ def __le__(self: NDArray[object_], other: Any) -> NDArray[bool_]: ...
+ @overload
+ def __le__(self: NDArray[Any], other: _ArrayLikeObject_co) -> NDArray[bool_]: ...
+
+ @overload
+ def __gt__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co) -> NDArray[bool_]: ...
+ @overload
+ def __gt__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[bool_]: ...
+ @overload
+ def __gt__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[bool_]: ...
+ @overload
+ def __gt__(self: NDArray[object_], other: Any) -> NDArray[bool_]: ...
+ @overload
+ def __gt__(self: NDArray[Any], other: _ArrayLikeObject_co) -> NDArray[bool_]: ...
+
+ @overload
+ def __ge__(self: _ArrayNumber_co, other: _ArrayLikeNumber_co) -> NDArray[bool_]: ...
+ @overload
+ def __ge__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[bool_]: ...
+ @overload
+ def __ge__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[bool_]: ...
+ @overload
+ def __ge__(self: NDArray[object_], other: Any) -> NDArray[bool_]: ...
+ @overload
+ def __ge__(self: NDArray[Any], other: _ArrayLikeObject_co) -> NDArray[bool_]: ...
+
+ # Unary ops
+ @overload
+ def __abs__(self: NDArray[bool_]) -> NDArray[bool_]: ...
+ @overload
+ def __abs__(self: NDArray[complexfloating[_NBit1, _NBit1]]) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __abs__(self: NDArray[_NumberType]) -> NDArray[_NumberType]: ...
+ @overload
+ def __abs__(self: NDArray[timedelta64]) -> NDArray[timedelta64]: ...
+ @overload
+ def __abs__(self: NDArray[object_]) -> Any: ...
+
+ @overload
+ def __invert__(self: NDArray[bool_]) -> NDArray[bool_]: ...
+ @overload
+ def __invert__(self: NDArray[_IntType]) -> NDArray[_IntType]: ...
+ @overload
+ def __invert__(self: NDArray[object_]) -> Any: ...
+
+ @overload
+ def __pos__(self: NDArray[_NumberType]) -> NDArray[_NumberType]: ...
+ @overload
+ def __pos__(self: NDArray[timedelta64]) -> NDArray[timedelta64]: ...
+ @overload
+ def __pos__(self: NDArray[object_]) -> Any: ...
+
+ @overload
+ def __neg__(self: NDArray[_NumberType]) -> NDArray[_NumberType]: ...
+ @overload
+ def __neg__(self: NDArray[timedelta64]) -> NDArray[timedelta64]: ...
+ @overload
+ def __neg__(self: NDArray[object_]) -> Any: ...
+
+ # Binary ops
+ # NOTE: `ndarray` does not implement `__imatmul__`
+ @overload
+ def __matmul__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __matmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __matmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __matmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __matmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+ @overload
+ def __matmul__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __matmul__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __matmul__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rmatmul__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __rmatmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmatmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmatmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmatmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+ @overload
+ def __rmatmul__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __rmatmul__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rmatmul__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __mod__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __mod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mod__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mod__(self: _ArrayTD64_co, other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[timedelta64]: ...
+ @overload
+ def __mod__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __mod__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rmod__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rmod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmod__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmod__(self: _ArrayTD64_co, other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[timedelta64]: ...
+ @overload
+ def __rmod__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rmod__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __divmod__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> _2Tuple[NDArray[int8]]: ... # type: ignore[misc]
+ @overload
+ def __divmod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> _2Tuple[NDArray[unsignedinteger[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __divmod__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> _2Tuple[NDArray[signedinteger[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __divmod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> _2Tuple[NDArray[floating[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __divmod__(self: _ArrayTD64_co, other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> tuple[NDArray[int64], NDArray[timedelta64]]: ...
+
+ @overload
+ def __rdivmod__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> _2Tuple[NDArray[int8]]: ... # type: ignore[misc]
+ @overload
+ def __rdivmod__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> _2Tuple[NDArray[unsignedinteger[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __rdivmod__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> _2Tuple[NDArray[signedinteger[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __rdivmod__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> _2Tuple[NDArray[floating[Any]]]: ... # type: ignore[misc]
+ @overload
+ def __rdivmod__(self: _ArrayTD64_co, other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> tuple[NDArray[int64], NDArray[timedelta64]]: ...
+
+ @overload
+ def __add__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __add__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ... # type: ignore[misc]
+ @overload
+ def __add__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __add__(self: NDArray[datetime64], other: _ArrayLikeTD64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __add__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __add__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __radd__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __radd__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ... # type: ignore[misc]
+ @overload
+ def __radd__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __radd__(self: NDArray[datetime64], other: _ArrayLikeTD64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __radd__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __radd__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __sub__(self: NDArray[_UnknownType], other: _ArrayLikeUnknown) -> NDArray[Any]: ...
+ @overload
+ def __sub__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __sub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __sub__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __sub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __sub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __sub__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __sub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ... # type: ignore[misc]
+ @overload
+ def __sub__(self: NDArray[datetime64], other: _ArrayLikeTD64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __sub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __sub__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __sub__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rsub__(self: NDArray[_UnknownType], other: _ArrayLikeUnknown) -> NDArray[Any]: ...
+ @overload
+ def __rsub__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __rsub__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: _ArrayTD64_co, other: _ArrayLikeDT64_co) -> NDArray[datetime64]: ... # type: ignore[misc]
+ @overload
+ def __rsub__(self: NDArray[datetime64], other: _ArrayLikeDT64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __rsub__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rsub__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __mul__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __mul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mul__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __mul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __mul__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __mul__(self: _ArrayTD64_co, other: _ArrayLikeFloat_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __mul__(self: _ArrayFloat_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __mul__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __mul__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rmul__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __rmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __rmul__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __rmul__(self: _ArrayTD64_co, other: _ArrayLikeFloat_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __rmul__(self: _ArrayFloat_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __rmul__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rmul__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __floordiv__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __floordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __floordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __floordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __floordiv__(self: NDArray[timedelta64], other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[int64]: ...
+ @overload
+ def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __floordiv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __floordiv__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __floordiv__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rfloordiv__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rfloordiv__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rfloordiv__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rfloordiv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rfloordiv__(self: NDArray[timedelta64], other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[int64]: ...
+ @overload
+ def __rfloordiv__(self: NDArray[bool_], other: _ArrayLikeTD64_co) -> NoReturn: ...
+ @overload
+ def __rfloordiv__(self: _ArrayFloat_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __rfloordiv__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rfloordiv__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __pow__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __pow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __pow__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __pow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __pow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+ @overload
+ def __pow__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __pow__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __pow__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rpow__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rpow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rpow__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rpow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rpow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+ @overload
+ def __rpow__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __rpow__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rpow__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __truediv__(self: _ArrayInt_co, other: _ArrayInt_co) -> NDArray[float64]: ... # type: ignore[misc]
+ @overload
+ def __truediv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __truediv__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __truediv__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __truediv__(self: NDArray[timedelta64], other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[float64]: ...
+ @overload
+ def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __truediv__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __truediv__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __truediv__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rtruediv__(self: _ArrayInt_co, other: _ArrayInt_co) -> NDArray[float64]: ... # type: ignore[misc]
+ @overload
+ def __rtruediv__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rtruediv__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ... # type: ignore[misc]
+ @overload
+ def __rtruediv__(self: NDArray[number[Any]], other: _ArrayLikeNumber_co) -> NDArray[number[Any]]: ...
+ @overload
+ def __rtruediv__(self: NDArray[timedelta64], other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[float64]: ...
+ @overload
+ def __rtruediv__(self: NDArray[bool_], other: _ArrayLikeTD64_co) -> NoReturn: ...
+ @overload
+ def __rtruediv__(self: _ArrayFloat_co, other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __rtruediv__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rtruediv__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __lshift__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __lshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __lshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __lshift__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __lshift__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rlshift__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rlshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rlshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __rlshift__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rlshift__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rshift__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __rshift__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rshift__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rrshift__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[int8]: ... # type: ignore[misc]
+ @overload
+ def __rrshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rrshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __rrshift__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rrshift__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __and__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __and__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __and__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __and__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __and__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rand__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __rand__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rand__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __rand__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rand__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __xor__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __xor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __xor__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __xor__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __xor__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __rxor__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __rxor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __rxor__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __rxor__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __rxor__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __or__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __or__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __or__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __or__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __or__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ @overload
+ def __ror__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ... # type: ignore[misc]
+ @overload
+ def __ror__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ... # type: ignore[misc]
+ @overload
+ def __ror__(self: _ArrayInt_co, other: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+ @overload
+ def __ror__(self: NDArray[object_], other: Any) -> Any: ...
+ @overload
+ def __ror__(self: NDArray[Any], other: _ArrayLikeObject_co) -> Any: ...
+
+ # `np.generic` does not support inplace operations
+
+ # NOTE: Inplace ops generally use "same_kind" casting w.r.t. to the left
+ # operand. An exception to this rule are unsigned integers though, which
+ # also accepts a signed integer for the right operand as long it is a 0D
+ # object and its value is >= 0
+ @overload
+ def __iadd__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ...
+ @overload
+ def __iadd__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __iadd__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __iadd__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __iadd__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __iadd__(self: NDArray[timedelta64], other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __iadd__(self: NDArray[datetime64], other: _ArrayLikeTD64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __iadd__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __isub__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __isub__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __isub__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __isub__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __isub__(self: NDArray[timedelta64], other: _ArrayLikeTD64_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __isub__(self: NDArray[datetime64], other: _ArrayLikeTD64_co) -> NDArray[datetime64]: ...
+ @overload
+ def __isub__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __imul__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ...
+ @overload
+ def __imul__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __imul__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __imul__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __imul__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __imul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __imul__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __itruediv__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __itruediv__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __itruediv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __itruediv__(self: NDArray[timedelta64], other: _ArrayLikeInt_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __itruediv__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __ifloordiv__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __ifloordiv__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __ifloordiv__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __ifloordiv__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __ifloordiv__(self: NDArray[timedelta64], other: _ArrayLikeBool_co) -> NoReturn: ...
+ @overload
+ def __ifloordiv__(self: NDArray[timedelta64], other: _ArrayLikeInt_co) -> NDArray[timedelta64]: ...
+ @overload
+ def __ifloordiv__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __ipow__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __ipow__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __ipow__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __ipow__(self: NDArray[complexfloating[_NBit1, _NBit1]], other: _ArrayLikeComplex_co) -> NDArray[complexfloating[_NBit1, _NBit1]]: ...
+ @overload
+ def __ipow__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __imod__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __imod__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __imod__(self: NDArray[floating[_NBit1]], other: _ArrayLikeFloat_co) -> NDArray[floating[_NBit1]]: ...
+ @overload
+ def __imod__(self: NDArray[timedelta64], other: _SupportsArray[_dtype[timedelta64]] | _NestedSequence[_SupportsArray[_dtype[timedelta64]]]) -> NDArray[timedelta64]: ...
+ @overload
+ def __imod__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __ilshift__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __ilshift__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __ilshift__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __irshift__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __irshift__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __irshift__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __iand__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ...
+ @overload
+ def __iand__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __iand__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __iand__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __ixor__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ...
+ @overload
+ def __ixor__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __ixor__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __ixor__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ @overload
+ def __ior__(self: NDArray[bool_], other: _ArrayLikeBool_co) -> NDArray[bool_]: ...
+ @overload
+ def __ior__(self: NDArray[unsignedinteger[_NBit1]], other: _ArrayLikeUInt_co | _IntLike_co) -> NDArray[unsignedinteger[_NBit1]]: ...
+ @overload
+ def __ior__(self: NDArray[signedinteger[_NBit1]], other: _ArrayLikeInt_co) -> NDArray[signedinteger[_NBit1]]: ...
+ @overload
+ def __ior__(self: NDArray[object_], other: Any) -> NDArray[object_]: ...
+
+ def __dlpack__(self: NDArray[number[Any]], *, stream: None = ...) -> _PyCapsule: ...
+ def __dlpack_device__(self) -> tuple[int, L[0]]: ...
+
+ # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype`
+ @property
+ def dtype(self) -> _DType_co: ...
+
+# NOTE: while `np.generic` is not technically an instance of `ABCMeta`,
+# the `@abstractmethod` decorator is herein used to (forcefully) deny
+# the creation of `np.generic` instances.
+# The `# type: ignore` comments are necessary to silence mypy errors regarding
+# the missing `ABCMeta` metaclass.
+
+# See https://github.com/numpy/numpy-stubs/pull/80 for more details.
+
+_ScalarType = TypeVar("_ScalarType", bound=generic)
+_NBit1 = TypeVar("_NBit1", bound=NBitBase)
+_NBit2 = TypeVar("_NBit2", bound=NBitBase)
+
+class generic(_ArrayOrScalarCommon):
+ @abstractmethod
+ def __init__(self, *args: Any, **kwargs: Any) -> None: ...
+ @overload
+ def __array__(self: _ScalarType, dtype: None = ..., /) -> ndarray[Any, _dtype[_ScalarType]]: ...
+ @overload
+ def __array__(self, dtype: _DType, /) -> ndarray[Any, _DType]: ...
+ @property
+ def base(self) -> None: ...
+ @property
+ def ndim(self) -> L[0]: ...
+ @property
+ def size(self) -> L[1]: ...
+ @property
+ def shape(self) -> tuple[()]: ...
+ @property
+ def strides(self) -> tuple[()]: ...
+ def byteswap(self: _ScalarType, inplace: L[False] = ...) -> _ScalarType: ...
+ @property
+ def flat(self: _ScalarType) -> flatiter[ndarray[Any, _dtype[_ScalarType]]]: ...
+
+ @overload
+ def astype(
+ self,
+ dtype: _DTypeLike[_ScalarType],
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ subok: bool = ...,
+ copy: bool | _CopyMode = ...,
+ ) -> _ScalarType: ...
+ @overload
+ def astype(
+ self,
+ dtype: DTypeLike,
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ subok: bool = ...,
+ copy: bool | _CopyMode = ...,
+ ) -> Any: ...
+
+ # NOTE: `view` will perform a 0D->scalar cast,
+ # thus the array `type` is irrelevant to the output type
+ @overload
+ def view(
+ self: _ScalarType,
+ type: type[ndarray[Any, Any]] = ...,
+ ) -> _ScalarType: ...
+ @overload
+ def view(
+ self,
+ dtype: _DTypeLike[_ScalarType],
+ type: type[ndarray[Any, Any]] = ...,
+ ) -> _ScalarType: ...
+ @overload
+ def view(
+ self,
+ dtype: DTypeLike,
+ type: type[ndarray[Any, Any]] = ...,
+ ) -> Any: ...
+
+ @overload
+ def getfield(
+ self,
+ dtype: _DTypeLike[_ScalarType],
+ offset: SupportsIndex = ...
+ ) -> _ScalarType: ...
+ @overload
+ def getfield(
+ self,
+ dtype: DTypeLike,
+ offset: SupportsIndex = ...
+ ) -> Any: ...
+
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> Any: ...
+
+ @overload
+ def take( # type: ignore[misc]
+ self: _ScalarType,
+ indices: _IntLike_co,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+ ) -> _ScalarType: ...
+ @overload
+ def take( # type: ignore[misc]
+ self: _ScalarType,
+ indices: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ out: None = ...,
+ mode: _ModeKind = ...,
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+ @overload
+ def take(
+ self,
+ indices: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ out: _NdArraySubClass = ...,
+ mode: _ModeKind = ...,
+ ) -> _NdArraySubClass: ...
+
+ def repeat(
+ self: _ScalarType,
+ repeats: _ArrayLikeInt_co,
+ axis: None | SupportsIndex = ...,
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+
+ def flatten(
+ self: _ScalarType,
+ order: _OrderKACF = ...,
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+
+ def ravel(
+ self: _ScalarType,
+ order: _OrderKACF = ...,
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+
+ @overload
+ def reshape(
+ self: _ScalarType, shape: _ShapeLike, /, *, order: _OrderACF = ...
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+ @overload
+ def reshape(
+ self: _ScalarType, *shape: SupportsIndex, order: _OrderACF = ...
+ ) -> ndarray[Any, _dtype[_ScalarType]]: ...
+
+ def squeeze(
+ self: _ScalarType, axis: None | L[0] | tuple[()] = ...
+ ) -> _ScalarType: ...
+ def transpose(self: _ScalarType, axes: None | tuple[()] = ..., /) -> _ScalarType: ...
+ # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype`
+ @property
+ def dtype(self: _ScalarType) -> _dtype[_ScalarType]: ...
+
+class number(generic, Generic[_NBit1]): # type: ignore
+ @property
+ def real(self: _ArraySelf) -> _ArraySelf: ...
+ @property
+ def imag(self: _ArraySelf) -> _ArraySelf: ...
+ if sys.version_info >= (3, 9):
+ def __class_getitem__(self, item: Any) -> GenericAlias: ...
+ def __int__(self) -> int: ...
+ def __float__(self) -> float: ...
+ def __complex__(self) -> complex: ...
+ def __neg__(self: _ArraySelf) -> _ArraySelf: ...
+ def __pos__(self: _ArraySelf) -> _ArraySelf: ...
+ def __abs__(self: _ArraySelf) -> _ArraySelf: ...
+ # Ensure that objects annotated as `number` support arithmetic operations
+ __add__: _NumberOp
+ __radd__: _NumberOp
+ __sub__: _NumberOp
+ __rsub__: _NumberOp
+ __mul__: _NumberOp
+ __rmul__: _NumberOp
+ __floordiv__: _NumberOp
+ __rfloordiv__: _NumberOp
+ __pow__: _NumberOp
+ __rpow__: _NumberOp
+ __truediv__: _NumberOp
+ __rtruediv__: _NumberOp
+ __lt__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __le__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __gt__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __ge__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+
+class bool_(generic):
+ def __init__(self, value: object = ..., /) -> None: ...
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> bool: ...
+ def tolist(self) -> bool: ...
+ @property
+ def real(self: _ArraySelf) -> _ArraySelf: ...
+ @property
+ def imag(self: _ArraySelf) -> _ArraySelf: ...
+ def __int__(self) -> int: ...
+ def __float__(self) -> float: ...
+ def __complex__(self) -> complex: ...
+ def __abs__(self: _ArraySelf) -> _ArraySelf: ...
+ __add__: _BoolOp[bool_]
+ __radd__: _BoolOp[bool_]
+ __sub__: _BoolSub
+ __rsub__: _BoolSub
+ __mul__: _BoolOp[bool_]
+ __rmul__: _BoolOp[bool_]
+ __floordiv__: _BoolOp[int8]
+ __rfloordiv__: _BoolOp[int8]
+ __pow__: _BoolOp[int8]
+ __rpow__: _BoolOp[int8]
+ __truediv__: _BoolTrueDiv
+ __rtruediv__: _BoolTrueDiv
+ def __invert__(self) -> bool_: ...
+ __lshift__: _BoolBitOp[int8]
+ __rlshift__: _BoolBitOp[int8]
+ __rshift__: _BoolBitOp[int8]
+ __rrshift__: _BoolBitOp[int8]
+ __and__: _BoolBitOp[bool_]
+ __rand__: _BoolBitOp[bool_]
+ __xor__: _BoolBitOp[bool_]
+ __rxor__: _BoolBitOp[bool_]
+ __or__: _BoolBitOp[bool_]
+ __ror__: _BoolBitOp[bool_]
+ __mod__: _BoolMod
+ __rmod__: _BoolMod
+ __divmod__: _BoolDivMod
+ __rdivmod__: _BoolDivMod
+ __lt__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __le__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __gt__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+ __ge__: _ComparisonOp[_NumberLike_co, _ArrayLikeNumber_co]
+
+class object_(generic):
+ def __init__(self, value: object = ..., /) -> None: ...
+ @property
+ def real(self: _ArraySelf) -> _ArraySelf: ...
+ @property
+ def imag(self: _ArraySelf) -> _ArraySelf: ...
+ # The 3 protocols below may or may not raise,
+ # depending on the underlying object
+ def __int__(self) -> int: ...
+ def __float__(self) -> float: ...
+ def __complex__(self) -> complex: ...
+
+# The `datetime64` constructors requires an object with the three attributes below,
+# and thus supports datetime duck typing
+class _DatetimeScalar(Protocol):
+ @property
+ def day(self) -> int: ...
+ @property
+ def month(self) -> int: ...
+ @property
+ def year(self) -> int: ...
+
+# TODO: `item`/`tolist` returns either `dt.date`, `dt.datetime` or `int`
+# depending on the unit
+class datetime64(generic):
+ @overload
+ def __init__(
+ self,
+ value: None | datetime64 | _CharLike_co | _DatetimeScalar = ...,
+ format: _CharLike_co | tuple[_CharLike_co, _IntLike_co] = ...,
+ /,
+ ) -> None: ...
+ @overload
+ def __init__(
+ self,
+ value: int,
+ format: _CharLike_co | tuple[_CharLike_co, _IntLike_co],
+ /,
+ ) -> None: ...
+ def __add__(self, other: _TD64Like_co) -> datetime64: ...
+ def __radd__(self, other: _TD64Like_co) -> datetime64: ...
+ @overload
+ def __sub__(self, other: datetime64) -> timedelta64: ...
+ @overload
+ def __sub__(self, other: _TD64Like_co) -> datetime64: ...
+ def __rsub__(self, other: datetime64) -> timedelta64: ...
+ __lt__: _ComparisonOp[datetime64, _ArrayLikeDT64_co]
+ __le__: _ComparisonOp[datetime64, _ArrayLikeDT64_co]
+ __gt__: _ComparisonOp[datetime64, _ArrayLikeDT64_co]
+ __ge__: _ComparisonOp[datetime64, _ArrayLikeDT64_co]
+
+_IntValue = Union[SupportsInt, _CharLike_co, SupportsIndex]
+_FloatValue = Union[None, _CharLike_co, SupportsFloat, SupportsIndex]
+_ComplexValue = Union[
+ None,
+ _CharLike_co,
+ SupportsFloat,
+ SupportsComplex,
+ SupportsIndex,
+ complex, # `complex` is not a subtype of `SupportsComplex`
+]
+
+class integer(number[_NBit1]): # type: ignore
+ @property
+ def numerator(self: _ScalarType) -> _ScalarType: ...
+ @property
+ def denominator(self) -> L[1]: ...
+ @overload
+ def __round__(self, ndigits: None = ...) -> int: ...
+ @overload
+ def __round__(self: _ScalarType, ndigits: SupportsIndex) -> _ScalarType: ...
+
+ # NOTE: `__index__` is technically defined in the bottom-most
+ # sub-classes (`int64`, `uint32`, etc)
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> int: ...
+ def tolist(self) -> int: ...
+ def is_integer(self) -> L[True]: ...
+ def bit_count(self: _ScalarType) -> int: ...
+ def __index__(self) -> int: ...
+ __truediv__: _IntTrueDiv[_NBit1]
+ __rtruediv__: _IntTrueDiv[_NBit1]
+ def __mod__(self, value: _IntLike_co) -> integer: ...
+ def __rmod__(self, value: _IntLike_co) -> integer: ...
+ def __invert__(self: _IntType) -> _IntType: ...
+ # Ensure that objects annotated as `integer` support bit-wise operations
+ def __lshift__(self, other: _IntLike_co) -> integer: ...
+ def __rlshift__(self, other: _IntLike_co) -> integer: ...
+ def __rshift__(self, other: _IntLike_co) -> integer: ...
+ def __rrshift__(self, other: _IntLike_co) -> integer: ...
+ def __and__(self, other: _IntLike_co) -> integer: ...
+ def __rand__(self, other: _IntLike_co) -> integer: ...
+ def __or__(self, other: _IntLike_co) -> integer: ...
+ def __ror__(self, other: _IntLike_co) -> integer: ...
+ def __xor__(self, other: _IntLike_co) -> integer: ...
+ def __rxor__(self, other: _IntLike_co) -> integer: ...
+
+class signedinteger(integer[_NBit1]):
+ def __init__(self, value: _IntValue = ..., /) -> None: ...
+ __add__: _SignedIntOp[_NBit1]
+ __radd__: _SignedIntOp[_NBit1]
+ __sub__: _SignedIntOp[_NBit1]
+ __rsub__: _SignedIntOp[_NBit1]
+ __mul__: _SignedIntOp[_NBit1]
+ __rmul__: _SignedIntOp[_NBit1]
+ __floordiv__: _SignedIntOp[_NBit1]
+ __rfloordiv__: _SignedIntOp[_NBit1]
+ __pow__: _SignedIntOp[_NBit1]
+ __rpow__: _SignedIntOp[_NBit1]
+ __lshift__: _SignedIntBitOp[_NBit1]
+ __rlshift__: _SignedIntBitOp[_NBit1]
+ __rshift__: _SignedIntBitOp[_NBit1]
+ __rrshift__: _SignedIntBitOp[_NBit1]
+ __and__: _SignedIntBitOp[_NBit1]
+ __rand__: _SignedIntBitOp[_NBit1]
+ __xor__: _SignedIntBitOp[_NBit1]
+ __rxor__: _SignedIntBitOp[_NBit1]
+ __or__: _SignedIntBitOp[_NBit1]
+ __ror__: _SignedIntBitOp[_NBit1]
+ __mod__: _SignedIntMod[_NBit1]
+ __rmod__: _SignedIntMod[_NBit1]
+ __divmod__: _SignedIntDivMod[_NBit1]
+ __rdivmod__: _SignedIntDivMod[_NBit1]
+
+int8 = signedinteger[_8Bit]
+int16 = signedinteger[_16Bit]
+int32 = signedinteger[_32Bit]
+int64 = signedinteger[_64Bit]
+
+byte = signedinteger[_NBitByte]
+short = signedinteger[_NBitShort]
+intc = signedinteger[_NBitIntC]
+intp = signedinteger[_NBitIntP]
+int_ = signedinteger[_NBitInt]
+longlong = signedinteger[_NBitLongLong]
+
+# TODO: `item`/`tolist` returns either `dt.timedelta` or `int`
+# depending on the unit
+class timedelta64(generic):
+ def __init__(
+ self,
+ value: None | int | _CharLike_co | dt.timedelta | timedelta64 = ...,
+ format: _CharLike_co | tuple[_CharLike_co, _IntLike_co] = ...,
+ /,
+ ) -> None: ...
+ @property
+ def numerator(self: _ScalarType) -> _ScalarType: ...
+ @property
+ def denominator(self) -> L[1]: ...
+
+ # NOTE: Only a limited number of units support conversion
+ # to builtin scalar types: `Y`, `M`, `ns`, `ps`, `fs`, `as`
+ def __int__(self) -> int: ...
+ def __float__(self) -> float: ...
+ def __complex__(self) -> complex: ...
+ def __neg__(self: _ArraySelf) -> _ArraySelf: ...
+ def __pos__(self: _ArraySelf) -> _ArraySelf: ...
+ def __abs__(self: _ArraySelf) -> _ArraySelf: ...
+ def __add__(self, other: _TD64Like_co) -> timedelta64: ...
+ def __radd__(self, other: _TD64Like_co) -> timedelta64: ...
+ def __sub__(self, other: _TD64Like_co) -> timedelta64: ...
+ def __rsub__(self, other: _TD64Like_co) -> timedelta64: ...
+ def __mul__(self, other: _FloatLike_co) -> timedelta64: ...
+ def __rmul__(self, other: _FloatLike_co) -> timedelta64: ...
+ __truediv__: _TD64Div[float64]
+ __floordiv__: _TD64Div[int64]
+ def __rtruediv__(self, other: timedelta64) -> float64: ...
+ def __rfloordiv__(self, other: timedelta64) -> int64: ...
+ def __mod__(self, other: timedelta64) -> timedelta64: ...
+ def __rmod__(self, other: timedelta64) -> timedelta64: ...
+ def __divmod__(self, other: timedelta64) -> tuple[int64, timedelta64]: ...
+ def __rdivmod__(self, other: timedelta64) -> tuple[int64, timedelta64]: ...
+ __lt__: _ComparisonOp[_TD64Like_co, _ArrayLikeTD64_co]
+ __le__: _ComparisonOp[_TD64Like_co, _ArrayLikeTD64_co]
+ __gt__: _ComparisonOp[_TD64Like_co, _ArrayLikeTD64_co]
+ __ge__: _ComparisonOp[_TD64Like_co, _ArrayLikeTD64_co]
+
+class unsignedinteger(integer[_NBit1]):
+ # NOTE: `uint64 + signedinteger -> float64`
+ def __init__(self, value: _IntValue = ..., /) -> None: ...
+ __add__: _UnsignedIntOp[_NBit1]
+ __radd__: _UnsignedIntOp[_NBit1]
+ __sub__: _UnsignedIntOp[_NBit1]
+ __rsub__: _UnsignedIntOp[_NBit1]
+ __mul__: _UnsignedIntOp[_NBit1]
+ __rmul__: _UnsignedIntOp[_NBit1]
+ __floordiv__: _UnsignedIntOp[_NBit1]
+ __rfloordiv__: _UnsignedIntOp[_NBit1]
+ __pow__: _UnsignedIntOp[_NBit1]
+ __rpow__: _UnsignedIntOp[_NBit1]
+ __lshift__: _UnsignedIntBitOp[_NBit1]
+ __rlshift__: _UnsignedIntBitOp[_NBit1]
+ __rshift__: _UnsignedIntBitOp[_NBit1]
+ __rrshift__: _UnsignedIntBitOp[_NBit1]
+ __and__: _UnsignedIntBitOp[_NBit1]
+ __rand__: _UnsignedIntBitOp[_NBit1]
+ __xor__: _UnsignedIntBitOp[_NBit1]
+ __rxor__: _UnsignedIntBitOp[_NBit1]
+ __or__: _UnsignedIntBitOp[_NBit1]
+ __ror__: _UnsignedIntBitOp[_NBit1]
+ __mod__: _UnsignedIntMod[_NBit1]
+ __rmod__: _UnsignedIntMod[_NBit1]
+ __divmod__: _UnsignedIntDivMod[_NBit1]
+ __rdivmod__: _UnsignedIntDivMod[_NBit1]
+
+uint8 = unsignedinteger[_8Bit]
+uint16 = unsignedinteger[_16Bit]
+uint32 = unsignedinteger[_32Bit]
+uint64 = unsignedinteger[_64Bit]
+
+ubyte = unsignedinteger[_NBitByte]
+ushort = unsignedinteger[_NBitShort]
+uintc = unsignedinteger[_NBitIntC]
+uintp = unsignedinteger[_NBitIntP]
+uint = unsignedinteger[_NBitInt]
+ulonglong = unsignedinteger[_NBitLongLong]
+
+class inexact(number[_NBit1]): # type: ignore
+ def __getnewargs__(self: inexact[_64Bit]) -> tuple[float, ...]: ...
+
+_IntType = TypeVar("_IntType", bound=integer)
+_FloatType = TypeVar('_FloatType', bound=floating)
+
+class floating(inexact[_NBit1]):
+ def __init__(self, value: _FloatValue = ..., /) -> None: ...
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ...,
+ /,
+ ) -> float: ...
+ def tolist(self) -> float: ...
+ def is_integer(self) -> bool: ...
+ def hex(self: float64) -> str: ...
+ @classmethod
+ def fromhex(cls: type[float64], string: str, /) -> float64: ...
+ def as_integer_ratio(self) -> tuple[int, int]: ...
+ if sys.version_info >= (3, 9):
+ def __ceil__(self: float64) -> int: ...
+ def __floor__(self: float64) -> int: ...
+ def __trunc__(self: float64) -> int: ...
+ def __getnewargs__(self: float64) -> tuple[float]: ...
+ def __getformat__(self: float64, typestr: L["double", "float"], /) -> str: ...
+ @overload
+ def __round__(self, ndigits: None = ...) -> int: ...
+ @overload
+ def __round__(self: _ScalarType, ndigits: SupportsIndex) -> _ScalarType: ...
+ __add__: _FloatOp[_NBit1]
+ __radd__: _FloatOp[_NBit1]
+ __sub__: _FloatOp[_NBit1]
+ __rsub__: _FloatOp[_NBit1]
+ __mul__: _FloatOp[_NBit1]
+ __rmul__: _FloatOp[_NBit1]
+ __truediv__: _FloatOp[_NBit1]
+ __rtruediv__: _FloatOp[_NBit1]
+ __floordiv__: _FloatOp[_NBit1]
+ __rfloordiv__: _FloatOp[_NBit1]
+ __pow__: _FloatOp[_NBit1]
+ __rpow__: _FloatOp[_NBit1]
+ __mod__: _FloatMod[_NBit1]
+ __rmod__: _FloatMod[_NBit1]
+ __divmod__: _FloatDivMod[_NBit1]
+ __rdivmod__: _FloatDivMod[_NBit1]
+
+float16 = floating[_16Bit]
+float32 = floating[_32Bit]
+float64 = floating[_64Bit]
+
+half = floating[_NBitHalf]
+single = floating[_NBitSingle]
+double = floating[_NBitDouble]
+float_ = floating[_NBitDouble]
+longdouble = floating[_NBitLongDouble]
+longfloat = floating[_NBitLongDouble]
+
+# The main reason for `complexfloating` having two typevars is cosmetic.
+# It is used to clarify why `complex128`s precision is `_64Bit`, the latter
+# describing the two 64 bit floats representing its real and imaginary component
+
+class complexfloating(inexact[_NBit1], Generic[_NBit1, _NBit2]):
+ def __init__(self, value: _ComplexValue = ..., /) -> None: ...
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> complex: ...
+ def tolist(self) -> complex: ...
+ @property
+ def real(self) -> floating[_NBit1]: ... # type: ignore[override]
+ @property
+ def imag(self) -> floating[_NBit2]: ... # type: ignore[override]
+ def __abs__(self) -> floating[_NBit1]: ... # type: ignore[override]
+ def __getnewargs__(self: complex128) -> tuple[float, float]: ...
+ # NOTE: Deprecated
+ # def __round__(self, ndigits=...): ...
+ __add__: _ComplexOp[_NBit1]
+ __radd__: _ComplexOp[_NBit1]
+ __sub__: _ComplexOp[_NBit1]
+ __rsub__: _ComplexOp[_NBit1]
+ __mul__: _ComplexOp[_NBit1]
+ __rmul__: _ComplexOp[_NBit1]
+ __truediv__: _ComplexOp[_NBit1]
+ __rtruediv__: _ComplexOp[_NBit1]
+ __pow__: _ComplexOp[_NBit1]
+ __rpow__: _ComplexOp[_NBit1]
+
+complex64 = complexfloating[_32Bit, _32Bit]
+complex128 = complexfloating[_64Bit, _64Bit]
+
+csingle = complexfloating[_NBitSingle, _NBitSingle]
+singlecomplex = complexfloating[_NBitSingle, _NBitSingle]
+cdouble = complexfloating[_NBitDouble, _NBitDouble]
+complex_ = complexfloating[_NBitDouble, _NBitDouble]
+cfloat = complexfloating[_NBitDouble, _NBitDouble]
+clongdouble = complexfloating[_NBitLongDouble, _NBitLongDouble]
+clongfloat = complexfloating[_NBitLongDouble, _NBitLongDouble]
+longcomplex = complexfloating[_NBitLongDouble, _NBitLongDouble]
+
+class flexible(generic): ... # type: ignore
+
+# TODO: `item`/`tolist` returns either `bytes` or `tuple`
+# depending on whether or not it's used as an opaque bytes sequence
+# or a structure
+class void(flexible):
+ @overload
+ def __init__(self, value: _IntLike_co | bytes, /, dtype : None = ...) -> None: ...
+ @overload
+ def __init__(self, value: Any, /, dtype: _DTypeLikeVoid) -> None: ...
+ @property
+ def real(self: _ArraySelf) -> _ArraySelf: ...
+ @property
+ def imag(self: _ArraySelf) -> _ArraySelf: ...
+ def setfield(
+ self, val: ArrayLike, dtype: DTypeLike, offset: int = ...
+ ) -> None: ...
+ @overload
+ def __getitem__(self, key: str | SupportsIndex) -> Any: ...
+ @overload
+ def __getitem__(self, key: list[str]) -> void: ...
+ def __setitem__(
+ self,
+ key: str | list[str] | SupportsIndex,
+ value: ArrayLike,
+ ) -> None: ...
+
+class character(flexible): # type: ignore
+ def __int__(self) -> int: ...
+ def __float__(self) -> float: ...
+
+# NOTE: Most `np.bytes_` / `np.str_` methods return their
+# builtin `bytes` / `str` counterpart
+
+class bytes_(character, bytes):
+ @overload
+ def __init__(self, value: object = ..., /) -> None: ...
+ @overload
+ def __init__(
+ self, value: str, /, encoding: str = ..., errors: str = ...
+ ) -> None: ...
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> bytes: ...
+ def tolist(self) -> bytes: ...
+
+string_ = bytes_
+
+class str_(character, str):
+ @overload
+ def __init__(self, value: object = ..., /) -> None: ...
+ @overload
+ def __init__(
+ self, value: bytes, /, encoding: str = ..., errors: str = ...
+ ) -> None: ...
+ def item(
+ self, args: L[0] | tuple[()] | tuple[L[0]] = ..., /,
+ ) -> str: ...
+ def tolist(self) -> str: ...
+
+unicode_ = str_
+
+#
+# Constants
+#
+
+Inf: Final[float]
+Infinity: Final[float]
+NAN: Final[float]
+NINF: Final[float]
+NZERO: Final[float]
+NaN: Final[float]
+PINF: Final[float]
+PZERO: Final[float]
+e: Final[float]
+euler_gamma: Final[float]
+inf: Final[float]
+infty: Final[float]
+nan: Final[float]
+pi: Final[float]
+
+ERR_IGNORE: L[0]
+ERR_WARN: L[1]
+ERR_RAISE: L[2]
+ERR_CALL: L[3]
+ERR_PRINT: L[4]
+ERR_LOG: L[5]
+ERR_DEFAULT: L[521]
+
+SHIFT_DIVIDEBYZERO: L[0]
+SHIFT_OVERFLOW: L[3]
+SHIFT_UNDERFLOW: L[6]
+SHIFT_INVALID: L[9]
+
+FPE_DIVIDEBYZERO: L[1]
+FPE_OVERFLOW: L[2]
+FPE_UNDERFLOW: L[4]
+FPE_INVALID: L[8]
+
+FLOATING_POINT_SUPPORT: L[1]
+UFUNC_BUFSIZE_DEFAULT = BUFSIZE
+
+little_endian: Final[bool]
+True_: Final[bool_]
+False_: Final[bool_]
+
+UFUNC_PYVALS_NAME: L["UFUNC_PYVALS"]
+
+newaxis: None
+
+# See `numpy._typing._ufunc` for more concrete nin-/nout-specific stubs
+@final
+class ufunc:
+ @property
+ def __name__(self) -> str: ...
+ @property
+ def __doc__(self) -> str: ...
+ __call__: Callable[..., Any]
+ @property
+ def nin(self) -> int: ...
+ @property
+ def nout(self) -> int: ...
+ @property
+ def nargs(self) -> int: ...
+ @property
+ def ntypes(self) -> int: ...
+ @property
+ def types(self) -> list[str]: ...
+ # Broad return type because it has to encompass things like
+ #
+ # >>> np.logical_and.identity is True
+ # True
+ # >>> np.add.identity is 0
+ # True
+ # >>> np.sin.identity is None
+ # True
+ #
+ # and any user-defined ufuncs.
+ @property
+ def identity(self) -> Any: ...
+ # This is None for ufuncs and a string for gufuncs.
+ @property
+ def signature(self) -> None | str: ...
+ # The next four methods will always exist, but they will just
+ # raise a ValueError ufuncs with that don't accept two input
+ # arguments and return one output argument. Because of that we
+ # can't type them very precisely.
+ reduce: Any
+ accumulate: Any
+ reduceat: Any
+ outer: Any
+ # Similarly at won't be defined for ufuncs that return multiple
+ # outputs, so we can't type it very precisely.
+ at: Any
+
+# Parameters: `__name__`, `ntypes` and `identity`
+absolute: _UFunc_Nin1_Nout1[L['absolute'], L[20], None]
+add: _UFunc_Nin2_Nout1[L['add'], L[22], L[0]]
+arccos: _UFunc_Nin1_Nout1[L['arccos'], L[8], None]
+arccosh: _UFunc_Nin1_Nout1[L['arccosh'], L[8], None]
+arcsin: _UFunc_Nin1_Nout1[L['arcsin'], L[8], None]
+arcsinh: _UFunc_Nin1_Nout1[L['arcsinh'], L[8], None]
+arctan2: _UFunc_Nin2_Nout1[L['arctan2'], L[5], None]
+arctan: _UFunc_Nin1_Nout1[L['arctan'], L[8], None]
+arctanh: _UFunc_Nin1_Nout1[L['arctanh'], L[8], None]
+bitwise_and: _UFunc_Nin2_Nout1[L['bitwise_and'], L[12], L[-1]]
+bitwise_not: _UFunc_Nin1_Nout1[L['invert'], L[12], None]
+bitwise_or: _UFunc_Nin2_Nout1[L['bitwise_or'], L[12], L[0]]
+bitwise_xor: _UFunc_Nin2_Nout1[L['bitwise_xor'], L[12], L[0]]
+cbrt: _UFunc_Nin1_Nout1[L['cbrt'], L[5], None]
+ceil: _UFunc_Nin1_Nout1[L['ceil'], L[7], None]
+conj: _UFunc_Nin1_Nout1[L['conjugate'], L[18], None]
+conjugate: _UFunc_Nin1_Nout1[L['conjugate'], L[18], None]
+copysign: _UFunc_Nin2_Nout1[L['copysign'], L[4], None]
+cos: _UFunc_Nin1_Nout1[L['cos'], L[9], None]
+cosh: _UFunc_Nin1_Nout1[L['cosh'], L[8], None]
+deg2rad: _UFunc_Nin1_Nout1[L['deg2rad'], L[5], None]
+degrees: _UFunc_Nin1_Nout1[L['degrees'], L[5], None]
+divide: _UFunc_Nin2_Nout1[L['true_divide'], L[11], None]
+divmod: _UFunc_Nin2_Nout2[L['divmod'], L[15], None]
+equal: _UFunc_Nin2_Nout1[L['equal'], L[23], None]
+exp2: _UFunc_Nin1_Nout1[L['exp2'], L[8], None]
+exp: _UFunc_Nin1_Nout1[L['exp'], L[10], None]
+expm1: _UFunc_Nin1_Nout1[L['expm1'], L[8], None]
+fabs: _UFunc_Nin1_Nout1[L['fabs'], L[5], None]
+float_power: _UFunc_Nin2_Nout1[L['float_power'], L[4], None]
+floor: _UFunc_Nin1_Nout1[L['floor'], L[7], None]
+floor_divide: _UFunc_Nin2_Nout1[L['floor_divide'], L[21], None]
+fmax: _UFunc_Nin2_Nout1[L['fmax'], L[21], None]
+fmin: _UFunc_Nin2_Nout1[L['fmin'], L[21], None]
+fmod: _UFunc_Nin2_Nout1[L['fmod'], L[15], None]
+frexp: _UFunc_Nin1_Nout2[L['frexp'], L[4], None]
+gcd: _UFunc_Nin2_Nout1[L['gcd'], L[11], L[0]]
+greater: _UFunc_Nin2_Nout1[L['greater'], L[23], None]
+greater_equal: _UFunc_Nin2_Nout1[L['greater_equal'], L[23], None]
+heaviside: _UFunc_Nin2_Nout1[L['heaviside'], L[4], None]
+hypot: _UFunc_Nin2_Nout1[L['hypot'], L[5], L[0]]
+invert: _UFunc_Nin1_Nout1[L['invert'], L[12], None]
+isfinite: _UFunc_Nin1_Nout1[L['isfinite'], L[20], None]
+isinf: _UFunc_Nin1_Nout1[L['isinf'], L[20], None]
+isnan: _UFunc_Nin1_Nout1[L['isnan'], L[20], None]
+isnat: _UFunc_Nin1_Nout1[L['isnat'], L[2], None]
+lcm: _UFunc_Nin2_Nout1[L['lcm'], L[11], None]
+ldexp: _UFunc_Nin2_Nout1[L['ldexp'], L[8], None]
+left_shift: _UFunc_Nin2_Nout1[L['left_shift'], L[11], None]
+less: _UFunc_Nin2_Nout1[L['less'], L[23], None]
+less_equal: _UFunc_Nin2_Nout1[L['less_equal'], L[23], None]
+log10: _UFunc_Nin1_Nout1[L['log10'], L[8], None]
+log1p: _UFunc_Nin1_Nout1[L['log1p'], L[8], None]
+log2: _UFunc_Nin1_Nout1[L['log2'], L[8], None]
+log: _UFunc_Nin1_Nout1[L['log'], L[10], None]
+logaddexp2: _UFunc_Nin2_Nout1[L['logaddexp2'], L[4], float]
+logaddexp: _UFunc_Nin2_Nout1[L['logaddexp'], L[4], float]
+logical_and: _UFunc_Nin2_Nout1[L['logical_and'], L[20], L[True]]
+logical_not: _UFunc_Nin1_Nout1[L['logical_not'], L[20], None]
+logical_or: _UFunc_Nin2_Nout1[L['logical_or'], L[20], L[False]]
+logical_xor: _UFunc_Nin2_Nout1[L['logical_xor'], L[19], L[False]]
+matmul: _GUFunc_Nin2_Nout1[L['matmul'], L[19], None]
+maximum: _UFunc_Nin2_Nout1[L['maximum'], L[21], None]
+minimum: _UFunc_Nin2_Nout1[L['minimum'], L[21], None]
+mod: _UFunc_Nin2_Nout1[L['remainder'], L[16], None]
+modf: _UFunc_Nin1_Nout2[L['modf'], L[4], None]
+multiply: _UFunc_Nin2_Nout1[L['multiply'], L[23], L[1]]
+negative: _UFunc_Nin1_Nout1[L['negative'], L[19], None]
+nextafter: _UFunc_Nin2_Nout1[L['nextafter'], L[4], None]
+not_equal: _UFunc_Nin2_Nout1[L['not_equal'], L[23], None]
+positive: _UFunc_Nin1_Nout1[L['positive'], L[19], None]
+power: _UFunc_Nin2_Nout1[L['power'], L[18], None]
+rad2deg: _UFunc_Nin1_Nout1[L['rad2deg'], L[5], None]
+radians: _UFunc_Nin1_Nout1[L['radians'], L[5], None]
+reciprocal: _UFunc_Nin1_Nout1[L['reciprocal'], L[18], None]
+remainder: _UFunc_Nin2_Nout1[L['remainder'], L[16], None]
+right_shift: _UFunc_Nin2_Nout1[L['right_shift'], L[11], None]
+rint: _UFunc_Nin1_Nout1[L['rint'], L[10], None]
+sign: _UFunc_Nin1_Nout1[L['sign'], L[19], None]
+signbit: _UFunc_Nin1_Nout1[L['signbit'], L[4], None]
+sin: _UFunc_Nin1_Nout1[L['sin'], L[9], None]
+sinh: _UFunc_Nin1_Nout1[L['sinh'], L[8], None]
+spacing: _UFunc_Nin1_Nout1[L['spacing'], L[4], None]
+sqrt: _UFunc_Nin1_Nout1[L['sqrt'], L[10], None]
+square: _UFunc_Nin1_Nout1[L['square'], L[18], None]
+subtract: _UFunc_Nin2_Nout1[L['subtract'], L[21], None]
+tan: _UFunc_Nin1_Nout1[L['tan'], L[8], None]
+tanh: _UFunc_Nin1_Nout1[L['tanh'], L[8], None]
+true_divide: _UFunc_Nin2_Nout1[L['true_divide'], L[11], None]
+trunc: _UFunc_Nin1_Nout1[L['trunc'], L[7], None]
+
+abs = absolute
+
+class _CopyMode(enum.Enum):
+ ALWAYS: L[True]
+ IF_NEEDED: L[False]
+ NEVER: L[2]
+
+# Warnings
+class ModuleDeprecationWarning(DeprecationWarning): ...
+class VisibleDeprecationWarning(UserWarning): ...
+class ComplexWarning(RuntimeWarning): ...
+class RankWarning(UserWarning): ...
+
+# Errors
+class TooHardError(RuntimeError): ...
+
+class AxisError(ValueError, IndexError):
+ axis: None | int
+ ndim: None | int
+ @overload
+ def __init__(self, axis: str, ndim: None = ..., msg_prefix: None = ...) -> None: ...
+ @overload
+ def __init__(self, axis: int, ndim: int, msg_prefix: None | str = ...) -> None: ...
+
+_CallType = TypeVar("_CallType", bound=_ErrFunc | _SupportsWrite[str])
+
+class errstate(Generic[_CallType], ContextDecorator):
+ call: _CallType
+ kwargs: _ErrDictOptional
+
+ # Expand `**kwargs` into explicit keyword-only arguments
+ def __init__(
+ self,
+ *,
+ call: _CallType = ...,
+ all: None | _ErrKind = ...,
+ divide: None | _ErrKind = ...,
+ over: None | _ErrKind = ...,
+ under: None | _ErrKind = ...,
+ invalid: None | _ErrKind = ...,
+ ) -> None: ...
+ def __enter__(self) -> None: ...
+ def __exit__(
+ self,
+ exc_type: None | type[BaseException],
+ exc_value: None | BaseException,
+ traceback: None | TracebackType,
+ /,
+ ) -> None: ...
+
+@contextmanager
+def _no_nep50_warning() -> Generator[None, None, None]: ...
+def _get_promotion_state() -> str: ...
+def _set_promotion_state(state: str, /) -> None: ...
+
+class ndenumerate(Generic[_ScalarType]):
+ iter: flatiter[NDArray[_ScalarType]]
+ @overload
+ def __new__(
+ cls, arr: _FiniteNestedSequence[_SupportsArray[dtype[_ScalarType]]],
+ ) -> ndenumerate[_ScalarType]: ...
+ @overload
+ def __new__(cls, arr: str | _NestedSequence[str]) -> ndenumerate[str_]: ...
+ @overload
+ def __new__(cls, arr: bytes | _NestedSequence[bytes]) -> ndenumerate[bytes_]: ...
+ @overload
+ def __new__(cls, arr: bool | _NestedSequence[bool]) -> ndenumerate[bool_]: ...
+ @overload
+ def __new__(cls, arr: int | _NestedSequence[int]) -> ndenumerate[int_]: ...
+ @overload
+ def __new__(cls, arr: float | _NestedSequence[float]) -> ndenumerate[float_]: ...
+ @overload
+ def __new__(cls, arr: complex | _NestedSequence[complex]) -> ndenumerate[complex_]: ...
+ def __next__(self: ndenumerate[_ScalarType]) -> tuple[_Shape, _ScalarType]: ...
+ def __iter__(self: _T) -> _T: ...
+
+class ndindex:
+ @overload
+ def __init__(self, shape: tuple[SupportsIndex, ...], /) -> None: ...
+ @overload
+ def __init__(self, *shape: SupportsIndex) -> None: ...
+ def __iter__(self: _T) -> _T: ...
+ def __next__(self) -> _Shape: ...
+
+class DataSource:
+ def __init__(
+ self,
+ destpath: None | str | os.PathLike[str] = ...,
+ ) -> 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: str = ...,
+ encoding: None | str = ...,
+ newline: None | str = ...,
+ ) -> IO[Any]: ...
+
+# TODO: The type of each `__next__` and `iters` return-type depends
+# on the length and dtype of `args`; we can't describe this behavior yet
+# as we lack variadics (PEP 646).
+@final
+class broadcast:
+ def __new__(cls, *args: ArrayLike) -> broadcast: ...
+ @property
+ def index(self) -> int: ...
+ @property
+ def iters(self) -> tuple[flatiter[Any], ...]: ...
+ @property
+ def nd(self) -> int: ...
+ @property
+ def ndim(self) -> int: ...
+ @property
+ def numiter(self) -> int: ...
+ @property
+ def shape(self) -> _Shape: ...
+ @property
+ def size(self) -> int: ...
+ def __next__(self) -> tuple[Any, ...]: ...
+ def __iter__(self: _T) -> _T: ...
+ def reset(self) -> None: ...
+
+@final
+class busdaycalendar:
+ def __new__(
+ cls,
+ weekmask: ArrayLike = ...,
+ holidays: ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
+ ) -> busdaycalendar: ...
+ @property
+ def weekmask(self) -> NDArray[bool_]: ...
+ @property
+ def holidays(self) -> NDArray[datetime64]: ...
+
+class finfo(Generic[_FloatType]):
+ dtype: dtype[_FloatType]
+ bits: int
+ eps: _FloatType
+ epsneg: _FloatType
+ iexp: int
+ machep: int
+ max: _FloatType
+ maxexp: int
+ min: _FloatType
+ minexp: int
+ negep: int
+ nexp: int
+ nmant: int
+ precision: int
+ resolution: _FloatType
+ smallest_subnormal: _FloatType
+ @property
+ def smallest_normal(self) -> _FloatType: ...
+ @property
+ def tiny(self) -> _FloatType: ...
+ @overload
+ def __new__(
+ cls, dtype: inexact[_NBit1] | _DTypeLike[inexact[_NBit1]]
+ ) -> finfo[floating[_NBit1]]: ...
+ @overload
+ def __new__(
+ cls, dtype: complex | float | type[complex] | type[float]
+ ) -> finfo[float_]: ...
+ @overload
+ def __new__(
+ cls, dtype: str
+ ) -> finfo[floating[Any]]: ...
+
+class iinfo(Generic[_IntType]):
+ dtype: dtype[_IntType]
+ kind: str
+ bits: int
+ key: str
+ @property
+ def min(self) -> int: ...
+ @property
+ def max(self) -> int: ...
+
+ @overload
+ def __new__(cls, dtype: _IntType | _DTypeLike[_IntType]) -> iinfo[_IntType]: ...
+ @overload
+ def __new__(cls, dtype: int | type[int]) -> iinfo[int_]: ...
+ @overload
+ def __new__(cls, dtype: str) -> iinfo[Any]: ...
+
+class format_parser:
+ dtype: dtype[void]
+ def __init__(
+ self,
+ formats: DTypeLike,
+ names: None | str | Sequence[str],
+ titles: None | str | Sequence[str],
+ aligned: bool = ...,
+ byteorder: None | _ByteOrder = ...,
+ ) -> None: ...
+
+class recarray(ndarray[_ShapeType, _DType_co]):
+ # NOTE: While not strictly mandatory, we're demanding here that arguments
+ # for the `format_parser`- and `dtype`-based dtype constructors are
+ # mutually exclusive
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: None = ...,
+ buf: None | _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: None | _ShapeLike = ...,
+ *,
+ formats: DTypeLike,
+ names: None | str | Sequence[str] = ...,
+ titles: None | str | Sequence[str] = ...,
+ byteorder: None | _ByteOrder = ...,
+ aligned: bool = ...,
+ order: _OrderKACF = ...,
+ ) -> recarray[Any, dtype[record]]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ dtype: DTypeLike,
+ buf: None | _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: None | _ShapeLike = ...,
+ formats: None = ...,
+ names: None = ...,
+ titles: None = ...,
+ byteorder: None = ...,
+ aligned: L[False] = ...,
+ order: _OrderKACF = ...,
+ ) -> recarray[Any, dtype[Any]]: ...
+ def __array_finalize__(self, obj: object) -> None: ...
+ def __getattribute__(self, attr: str) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike) -> None: ...
+ @overload
+ def __getitem__(self, indx: (
+ SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[SupportsIndex | _ArrayLikeInt_co, ...]
+ )) -> Any: ...
+ @overload
+ def __getitem__(self: recarray[Any, dtype[void]], indx: (
+ None
+ | slice
+ | ellipsis
+ | SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...]
+ )) -> recarray[Any, _DType_co]: ...
+ @overload
+ def __getitem__(self, indx: (
+ None
+ | slice
+ | ellipsis
+ | SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...]
+ )) -> ndarray[Any, _DType_co]: ...
+ @overload
+ def __getitem__(self, indx: str) -> NDArray[Any]: ...
+ @overload
+ def __getitem__(self, indx: list[str]) -> recarray[_ShapeType, dtype[record]]: ...
+ @overload
+ def field(self, attr: int | str, val: None = ...) -> Any: ...
+ @overload
+ def field(self, attr: int | str, val: ArrayLike) -> None: ...
+
+class record(void):
+ def __getattribute__(self, attr: str) -> Any: ...
+ def __setattr__(self, attr: str, val: ArrayLike) -> None: ...
+ def pprint(self) -> str: ...
+ @overload
+ def __getitem__(self, key: str | SupportsIndex) -> Any: ...
+ @overload
+ def __getitem__(self, key: list[str]) -> record: ...
+
+_NDIterFlagsKind = L[
+ "buffered",
+ "c_index",
+ "copy_if_overlap",
+ "common_dtype",
+ "delay_bufalloc",
+ "external_loop",
+ "f_index",
+ "grow_inner", "growinner",
+ "multi_index",
+ "ranged",
+ "refs_ok",
+ "reduce_ok",
+ "zerosize_ok",
+]
+
+_NDIterOpFlagsKind = L[
+ "aligned",
+ "allocate",
+ "arraymask",
+ "copy",
+ "config",
+ "nbo",
+ "no_subtype",
+ "no_broadcast",
+ "overlap_assume_elementwise",
+ "readonly",
+ "readwrite",
+ "updateifcopy",
+ "virtual",
+ "writeonly",
+ "writemasked"
+]
+
+@final
+class nditer:
+ def __new__(
+ cls,
+ op: ArrayLike | Sequence[ArrayLike],
+ flags: None | Sequence[_NDIterFlagsKind] = ...,
+ op_flags: None | Sequence[Sequence[_NDIterOpFlagsKind]] = ...,
+ op_dtypes: DTypeLike | Sequence[DTypeLike] = ...,
+ order: _OrderKACF = ...,
+ casting: _CastingKind = ...,
+ op_axes: None | Sequence[Sequence[SupportsIndex]] = ...,
+ itershape: None | _ShapeLike = ...,
+ buffersize: SupportsIndex = ...,
+ ) -> nditer: ...
+ def __enter__(self) -> nditer: ...
+ def __exit__(
+ self,
+ exc_type: None | type[BaseException],
+ exc_value: None | BaseException,
+ traceback: None | TracebackType,
+ ) -> None: ...
+ def __iter__(self) -> nditer: ...
+ def __next__(self) -> tuple[NDArray[Any], ...]: ...
+ def __len__(self) -> int: ...
+ def __copy__(self) -> nditer: ...
+ @overload
+ def __getitem__(self, index: SupportsIndex) -> NDArray[Any]: ...
+ @overload
+ def __getitem__(self, index: slice) -> tuple[NDArray[Any], ...]: ...
+ def __setitem__(self, index: slice | SupportsIndex, value: ArrayLike) -> None: ...
+ def close(self) -> None: ...
+ def copy(self) -> nditer: ...
+ def debug_print(self) -> None: ...
+ def enable_external_loop(self) -> None: ...
+ def iternext(self) -> bool: ...
+ def remove_axis(self, i: SupportsIndex, /) -> None: ...
+ def remove_multi_index(self) -> None: ...
+ def reset(self) -> None: ...
+ @property
+ def dtypes(self) -> tuple[dtype[Any], ...]: ...
+ @property
+ def finished(self) -> bool: ...
+ @property
+ def has_delayed_bufalloc(self) -> bool: ...
+ @property
+ def has_index(self) -> bool: ...
+ @property
+ def has_multi_index(self) -> bool: ...
+ @property
+ def index(self) -> int: ...
+ @property
+ def iterationneedsapi(self) -> bool: ...
+ @property
+ def iterindex(self) -> int: ...
+ @property
+ def iterrange(self) -> tuple[int, ...]: ...
+ @property
+ def itersize(self) -> int: ...
+ @property
+ def itviews(self) -> tuple[NDArray[Any], ...]: ...
+ @property
+ def multi_index(self) -> tuple[int, ...]: ...
+ @property
+ def ndim(self) -> int: ...
+ @property
+ def nop(self) -> int: ...
+ @property
+ def operands(self) -> tuple[NDArray[Any], ...]: ...
+ @property
+ def shape(self) -> tuple[int, ...]: ...
+ @property
+ def value(self) -> tuple[NDArray[Any], ...]: ...
+
+_MemMapModeKind = L[
+ "readonly", "r",
+ "copyonwrite", "c",
+ "readwrite", "r+",
+ "write", "w+",
+]
+
+class memmap(ndarray[_ShapeType, _DType_co]):
+ __array_priority__: ClassVar[float]
+ filename: str | None
+ offset: int
+ mode: str
+ @overload
+ def __new__(
+ subtype,
+ filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
+ dtype: type[uint8] = ...,
+ mode: _MemMapModeKind = ...,
+ offset: int = ...,
+ shape: None | int | tuple[int, ...] = ...,
+ order: _OrderKACF = ...,
+ ) -> memmap[Any, dtype[uint8]]: ...
+ @overload
+ def __new__(
+ subtype,
+ filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
+ dtype: _DTypeLike[_ScalarType],
+ mode: _MemMapModeKind = ...,
+ offset: int = ...,
+ shape: None | int | tuple[int, ...] = ...,
+ order: _OrderKACF = ...,
+ ) -> memmap[Any, dtype[_ScalarType]]: ...
+ @overload
+ def __new__(
+ subtype,
+ filename: str | bytes | os.PathLike[str] | os.PathLike[bytes] | _MemMapIOProtocol,
+ dtype: DTypeLike,
+ mode: _MemMapModeKind = ...,
+ offset: int = ...,
+ shape: None | int | tuple[int, ...] = ...,
+ order: _OrderKACF = ...,
+ ) -> memmap[Any, dtype[Any]]: ...
+ def __array_finalize__(self, obj: object) -> None: ...
+ def __array_wrap__(
+ self,
+ array: memmap[_ShapeType, _DType_co],
+ context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+ ) -> Any: ...
+ def flush(self) -> None: ...
+
+# TODO: Add a mypy plugin for managing functions whose output type is dependent
+# on the literal value of some sort of signature (e.g. `einsum` and `vectorize`)
+class vectorize:
+ pyfunc: Callable[..., Any]
+ cache: bool
+ signature: None | str
+ otypes: None | str
+ excluded: set[int | str]
+ __doc__: None | str
+ def __init__(
+ self,
+ pyfunc: Callable[..., Any],
+ otypes: None | str | Iterable[DTypeLike] = ...,
+ doc: None | str = ...,
+ excluded: None | Iterable[int | str] = ...,
+ cache: bool = ...,
+ signature: None | str = ...,
+ ) -> None: ...
+ def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
+
+class poly1d:
+ @property
+ def variable(self) -> str: ...
+ @property
+ def order(self) -> int: ...
+ @property
+ def o(self) -> int: ...
+ @property
+ def roots(self) -> NDArray[Any]: ...
+ @property
+ def r(self) -> NDArray[Any]: ...
+
+ @property
+ def coeffs(self) -> NDArray[Any]: ...
+ @coeffs.setter
+ def coeffs(self, value: NDArray[Any]) -> None: ...
+
+ @property
+ def c(self) -> NDArray[Any]: ...
+ @c.setter
+ def c(self, value: NDArray[Any]) -> None: ...
+
+ @property
+ def coef(self) -> NDArray[Any]: ...
+ @coef.setter
+ def coef(self, value: NDArray[Any]) -> None: ...
+
+ @property
+ def coefficients(self) -> NDArray[Any]: ...
+ @coefficients.setter
+ def coefficients(self, value: NDArray[Any]) -> None: ...
+
+ __hash__: ClassVar[None] # type: ignore
+
+ @overload
+ def __array__(self, t: None = ...) -> NDArray[Any]: ...
+ @overload
+ def __array__(self, t: _DType) -> ndarray[Any, _DType]: ...
+
+ @overload
+ def __call__(self, val: _ScalarLike_co) -> Any: ...
+ @overload
+ def __call__(self, val: poly1d) -> poly1d: ...
+ @overload
+ def __call__(self, val: ArrayLike) -> NDArray[Any]: ...
+
+ def __init__(
+ self,
+ c_or_r: ArrayLike,
+ r: bool = ...,
+ variable: None | str = ...,
+ ) -> None: ...
+ def __len__(self) -> int: ...
+ def __neg__(self) -> poly1d: ...
+ def __pos__(self) -> poly1d: ...
+ def __mul__(self, other: ArrayLike) -> poly1d: ...
+ def __rmul__(self, other: ArrayLike) -> poly1d: ...
+ def __add__(self, other: ArrayLike) -> poly1d: ...
+ def __radd__(self, other: ArrayLike) -> poly1d: ...
+ def __pow__(self, val: _FloatLike_co) -> poly1d: ... # Integral floats are accepted
+ def __sub__(self, other: ArrayLike) -> poly1d: ...
+ def __rsub__(self, other: ArrayLike) -> poly1d: ...
+ def __div__(self, other: ArrayLike) -> poly1d: ...
+ def __truediv__(self, other: ArrayLike) -> poly1d: ...
+ def __rdiv__(self, other: ArrayLike) -> poly1d: ...
+ def __rtruediv__(self, other: ArrayLike) -> poly1d: ...
+ def __getitem__(self, val: int) -> Any: ...
+ def __setitem__(self, key: int, val: Any) -> None: ...
+ def __iter__(self) -> Iterator[Any]: ...
+ def deriv(self, m: SupportsInt | SupportsIndex = ...) -> poly1d: ...
+ def integ(
+ self,
+ m: SupportsInt | SupportsIndex = ...,
+ k: None | _ArrayLikeComplex_co | _ArrayLikeObject_co = ...,
+ ) -> poly1d: ...
+
+class matrix(ndarray[_ShapeType, _DType_co]):
+ __array_priority__: ClassVar[float]
+ def __new__(
+ subtype,
+ data: ArrayLike,
+ dtype: DTypeLike = ...,
+ copy: bool = ...,
+ ) -> matrix[Any, Any]: ...
+ def __array_finalize__(self, obj: object) -> None: ...
+
+ @overload
+ def __getitem__(self, key: (
+ SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[SupportsIndex | _ArrayLikeInt_co, ...]
+ )) -> Any: ...
+ @overload
+ def __getitem__(self, key: (
+ None
+ | slice
+ | ellipsis
+ | SupportsIndex
+ | _ArrayLikeInt_co
+ | tuple[None | slice | ellipsis | _ArrayLikeInt_co | SupportsIndex, ...]
+ )) -> matrix[Any, _DType_co]: ...
+ @overload
+ def __getitem__(self: NDArray[void], key: str) -> matrix[Any, dtype[Any]]: ...
+ @overload
+ def __getitem__(self: NDArray[void], key: list[str]) -> matrix[_ShapeType, dtype[void]]: ...
+
+ def __mul__(self, other: ArrayLike) -> matrix[Any, Any]: ...
+ def __rmul__(self, other: ArrayLike) -> matrix[Any, Any]: ...
+ def __imul__(self, other: ArrayLike) -> matrix[_ShapeType, _DType_co]: ...
+ def __pow__(self, other: ArrayLike) -> matrix[Any, Any]: ...
+ def __ipow__(self, other: ArrayLike) -> matrix[_ShapeType, _DType_co]: ...
+
+ @overload
+ def sum(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ...) -> Any: ...
+ @overload
+ def sum(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[Any, Any]: ...
+ @overload
+ def sum(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def mean(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ...) -> Any: ...
+ @overload
+ def mean(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[Any, Any]: ...
+ @overload
+ def mean(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def std(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> Any: ...
+ @overload
+ def std(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> matrix[Any, Any]: ...
+ @overload
+ def std(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _NdArraySubClass = ..., ddof: float = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def var(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> Any: ...
+ @overload
+ def var(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> matrix[Any, Any]: ...
+ @overload
+ def var(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _NdArraySubClass = ..., ddof: float = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def prod(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ...) -> Any: ...
+ @overload
+ def prod(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[Any, Any]: ...
+ @overload
+ def prod(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def any(self, axis: None = ..., out: None = ...) -> bool_: ...
+ @overload
+ def any(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, dtype[bool_]]: ...
+ @overload
+ def any(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def all(self, axis: None = ..., out: None = ...) -> bool_: ...
+ @overload
+ def all(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, dtype[bool_]]: ...
+ @overload
+ def all(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def max(self: NDArray[_ScalarType], axis: None = ..., out: None = ...) -> _ScalarType: ...
+ @overload
+ def max(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, _DType_co]: ...
+ @overload
+ def max(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def min(self: NDArray[_ScalarType], axis: None = ..., out: None = ...) -> _ScalarType: ...
+ @overload
+ def min(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, _DType_co]: ...
+ @overload
+ def min(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def argmax(self: NDArray[_ScalarType], axis: None = ..., out: None = ...) -> intp: ...
+ @overload
+ def argmax(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, dtype[intp]]: ...
+ @overload
+ def argmax(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def argmin(self: NDArray[_ScalarType], axis: None = ..., out: None = ...) -> intp: ...
+ @overload
+ def argmin(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, dtype[intp]]: ...
+ @overload
+ def argmin(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ @overload
+ def ptp(self: NDArray[_ScalarType], axis: None = ..., out: None = ...) -> _ScalarType: ...
+ @overload
+ def ptp(self, axis: _ShapeLike, out: None = ...) -> matrix[Any, _DType_co]: ...
+ @overload
+ def ptp(self, axis: None | _ShapeLike = ..., out: _NdArraySubClass = ...) -> _NdArraySubClass: ...
+
+ def squeeze(self, axis: None | _ShapeLike = ...) -> matrix[Any, _DType_co]: ...
+ def tolist(self: matrix[Any, dtype[_SupportsItem[_T]]]) -> list[list[_T]]: ... # type: ignore[typevar]
+ def ravel(self, order: _OrderKACF = ...) -> matrix[Any, _DType_co]: ...
+ def flatten(self, order: _OrderKACF = ...) -> matrix[Any, _DType_co]: ...
+
+ @property
+ def T(self) -> matrix[Any, _DType_co]: ...
+ @property
+ def I(self) -> matrix[Any, Any]: ...
+ @property
+ def A(self) -> ndarray[_ShapeType, _DType_co]: ...
+ @property
+ def A1(self) -> ndarray[Any, _DType_co]: ...
+ @property
+ def H(self) -> matrix[Any, _DType_co]: ...
+ def getT(self) -> matrix[Any, _DType_co]: ...
+ def getI(self) -> matrix[Any, Any]: ...
+ def getA(self) -> ndarray[_ShapeType, _DType_co]: ...
+ def getA1(self) -> ndarray[Any, _DType_co]: ...
+ def getH(self) -> matrix[Any, _DType_co]: ...
+
+_CharType = TypeVar("_CharType", str_, bytes_)
+_CharDType = TypeVar("_CharDType", dtype[str_], dtype[bytes_])
+_CharArray = chararray[Any, dtype[_CharType]]
+
+class chararray(ndarray[_ShapeType, _CharDType]):
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ itemsize: SupportsIndex | SupportsInt = ...,
+ unicode: L[False] = ...,
+ buffer: _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: _ShapeLike = ...,
+ order: _OrderKACF = ...,
+ ) -> chararray[Any, dtype[bytes_]]: ...
+ @overload
+ def __new__(
+ subtype,
+ shape: _ShapeLike,
+ itemsize: SupportsIndex | SupportsInt = ...,
+ unicode: L[True] = ...,
+ buffer: _SupportsBuffer = ...,
+ offset: SupportsIndex = ...,
+ strides: _ShapeLike = ...,
+ order: _OrderKACF = ...,
+ ) -> chararray[Any, dtype[str_]]: ...
+
+ def __array_finalize__(self, obj: object) -> None: ...
+ def __mul__(self, other: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ...
+ def __rmul__(self, other: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ...
+ def __mod__(self, i: Any) -> chararray[Any, _CharDType]: ...
+
+ @overload
+ def __eq__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __eq__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __ne__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __ne__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __ge__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __ge__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __le__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __le__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __gt__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __gt__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __lt__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def __lt__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def __add__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __add__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def __radd__(
+ self: _CharArray[str_],
+ other: _ArrayLikeStr_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def __radd__(
+ self: _CharArray[bytes_],
+ other: _ArrayLikeBytes_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def center(
+ self: _CharArray[str_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def center(
+ self: _CharArray[bytes_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def count(
+ self: _CharArray[str_],
+ sub: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def count(
+ self: _CharArray[bytes_],
+ sub: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+
+ def decode(
+ self: _CharArray[bytes_],
+ encoding: None | str = ...,
+ errors: None | str = ...,
+ ) -> _CharArray[str_]: ...
+
+ def encode(
+ self: _CharArray[str_],
+ encoding: None | str = ...,
+ errors: None | str = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def endswith(
+ self: _CharArray[str_],
+ suffix: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def endswith(
+ self: _CharArray[bytes_],
+ suffix: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[bool_]: ...
+
+ def expandtabs(
+ self,
+ tabsize: _ArrayLikeInt_co = ...,
+ ) -> chararray[Any, _CharDType]: ...
+
+ @overload
+ def find(
+ self: _CharArray[str_],
+ sub: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def find(
+ self: _CharArray[bytes_],
+ sub: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def index(
+ self: _CharArray[str_],
+ sub: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def index(
+ self: _CharArray[bytes_],
+ sub: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def join(
+ self: _CharArray[str_],
+ seq: _ArrayLikeStr_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def join(
+ self: _CharArray[bytes_],
+ seq: _ArrayLikeBytes_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def ljust(
+ self: _CharArray[str_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def ljust(
+ self: _CharArray[bytes_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def lstrip(
+ self: _CharArray[str_],
+ chars: None | _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def lstrip(
+ self: _CharArray[bytes_],
+ chars: None | _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def partition(
+ self: _CharArray[str_],
+ sep: _ArrayLikeStr_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def partition(
+ self: _CharArray[bytes_],
+ sep: _ArrayLikeBytes_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def replace(
+ self: _CharArray[str_],
+ old: _ArrayLikeStr_co,
+ new: _ArrayLikeStr_co,
+ count: None | _ArrayLikeInt_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def replace(
+ self: _CharArray[bytes_],
+ old: _ArrayLikeBytes_co,
+ new: _ArrayLikeBytes_co,
+ count: None | _ArrayLikeInt_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rfind(
+ self: _CharArray[str_],
+ sub: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rfind(
+ self: _CharArray[bytes_],
+ sub: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rindex(
+ self: _CharArray[str_],
+ sub: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+ @overload
+ def rindex(
+ self: _CharArray[bytes_],
+ sub: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[int_]: ...
+
+ @overload
+ def rjust(
+ self: _CharArray[str_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rjust(
+ self: _CharArray[bytes_],
+ width: _ArrayLikeInt_co,
+ fillchar: _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rpartition(
+ self: _CharArray[str_],
+ sep: _ArrayLikeStr_co,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rpartition(
+ self: _CharArray[bytes_],
+ sep: _ArrayLikeBytes_co,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def rsplit(
+ self: _CharArray[str_],
+ sep: None | _ArrayLikeStr_co = ...,
+ maxsplit: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[object_]: ...
+ @overload
+ def rsplit(
+ self: _CharArray[bytes_],
+ sep: None | _ArrayLikeBytes_co = ...,
+ maxsplit: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[object_]: ...
+
+ @overload
+ def rstrip(
+ self: _CharArray[str_],
+ chars: None | _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def rstrip(
+ self: _CharArray[bytes_],
+ chars: None | _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def split(
+ self: _CharArray[str_],
+ sep: None | _ArrayLikeStr_co = ...,
+ maxsplit: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[object_]: ...
+ @overload
+ def split(
+ self: _CharArray[bytes_],
+ sep: None | _ArrayLikeBytes_co = ...,
+ maxsplit: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[object_]: ...
+
+ def splitlines(self, keepends: None | _ArrayLikeBool_co = ...) -> NDArray[object_]: ...
+
+ @overload
+ def startswith(
+ self: _CharArray[str_],
+ prefix: _ArrayLikeStr_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[bool_]: ...
+ @overload
+ def startswith(
+ self: _CharArray[bytes_],
+ prefix: _ArrayLikeBytes_co,
+ start: _ArrayLikeInt_co = ...,
+ end: None | _ArrayLikeInt_co = ...,
+ ) -> NDArray[bool_]: ...
+
+ @overload
+ def strip(
+ self: _CharArray[str_],
+ chars: None | _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def strip(
+ self: _CharArray[bytes_],
+ chars: None | _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ @overload
+ def translate(
+ self: _CharArray[str_],
+ table: _ArrayLikeStr_co,
+ deletechars: None | _ArrayLikeStr_co = ...,
+ ) -> _CharArray[str_]: ...
+ @overload
+ def translate(
+ self: _CharArray[bytes_],
+ table: _ArrayLikeBytes_co,
+ deletechars: None | _ArrayLikeBytes_co = ...,
+ ) -> _CharArray[bytes_]: ...
+
+ def zfill(self, width: _ArrayLikeInt_co) -> chararray[Any, _CharDType]: ...
+ def capitalize(self) -> chararray[_ShapeType, _CharDType]: ...
+ def title(self) -> chararray[_ShapeType, _CharDType]: ...
+ def swapcase(self) -> chararray[_ShapeType, _CharDType]: ...
+ def lower(self) -> chararray[_ShapeType, _CharDType]: ...
+ def upper(self) -> chararray[_ShapeType, _CharDType]: ...
+ def isalnum(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isalpha(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isdigit(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def islower(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isspace(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def istitle(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isupper(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isnumeric(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+ def isdecimal(self) -> ndarray[_ShapeType, dtype[bool_]]: ...
+
+# NOTE: Deprecated
+# class MachAr: ...
+
+class _SupportsDLPack(Protocol[_T_contra]):
+ def __dlpack__(self, *, stream: None | _T_contra = ...) -> _PyCapsule: ...
+
+def from_dlpack(obj: _SupportsDLPack[None], /) -> NDArray[Any]: ...
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_distributor_init.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_distributor_init.py
new file mode 100644
index 0000000000000000000000000000000000000000..d893ba37719b8dbab2ac34d35ae2b9cc2d331027
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_distributor_init.py
@@ -0,0 +1,10 @@
+""" Distributor init file
+
+Distributors: you can add custom code here to support particular distributions
+of numpy.
+
+For example, this is a good place to put any checks for hardware requirements.
+
+The numpy standard source distribution will not put code in this file, so you
+can safely replace this file with your own version.
+"""
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_globals.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_globals.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e4f26cd86a42d7da78a882a472eb58bec1cb7f7
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_globals.py
@@ -0,0 +1,125 @@
+"""
+Module defining global singleton classes.
+
+This module raises a RuntimeError if an attempt to reload it is made. In that
+way the identities of the classes defined here are fixed and will remain so
+even if numpy itself is reloaded. In particular, a function like the following
+will still work correctly after numpy is reloaded::
+
+ def foo(arg=np._NoValue):
+ if arg is np._NoValue:
+ ...
+
+That was not the case when the singleton classes were defined in the numpy
+``__init__.py`` file. See gh-7844 for a discussion of the reload problem that
+motivated this module.
+
+"""
+import enum
+
+__ALL__ = [
+ 'ModuleDeprecationWarning', 'VisibleDeprecationWarning',
+ '_NoValue', '_CopyMode'
+ ]
+
+
+# Disallow reloading this module so as to preserve the identities of the
+# classes defined here.
+if '_is_loaded' in globals():
+ raise RuntimeError('Reloading numpy._globals is not allowed')
+_is_loaded = True
+
+
+class ModuleDeprecationWarning(DeprecationWarning):
+ """Module deprecation warning.
+
+ The nose tester turns ordinary Deprecation warnings into test failures.
+ That makes it hard to deprecate whole modules, because they get
+ imported by default. So this is a special Deprecation warning that the
+ nose tester will let pass without making tests fail.
+
+ """
+
+
+ModuleDeprecationWarning.__module__ = 'numpy'
+
+
+class VisibleDeprecationWarning(UserWarning):
+ """Visible deprecation warning.
+
+ By default, python will not show deprecation warnings, so this class
+ can be used when a very visible warning is helpful, for example because
+ the usage is most likely a user bug.
+
+ """
+
+
+VisibleDeprecationWarning.__module__ = 'numpy'
+
+
+class _NoValueType:
+ """Special keyword value.
+
+ The instance of this class may be used as the default value assigned to a
+ keyword if no other obvious default (e.g., `None`) is suitable,
+
+ Common reasons for using this keyword are:
+
+ - A new keyword is added to a function, and that function forwards its
+ inputs to another function or method which can be defined outside of
+ NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims``
+ keyword was added that could only be forwarded if the user explicitly
+ specified ``keepdims``; downstream array libraries may not have added
+ the same keyword, so adding ``x.std(..., keepdims=keepdims)``
+ unconditionally could have broken previously working code.
+ - A keyword is being deprecated, and a deprecation warning must only be
+ emitted when the keyword is used.
+
+ """
+ __instance = None
+ def __new__(cls):
+ # ensure that only one instance exists
+ if not cls.__instance:
+ cls.__instance = super().__new__(cls)
+ return cls.__instance
+
+ def __repr__(self):
+ return ""
+
+
+_NoValue = _NoValueType()
+
+
+class _CopyMode(enum.Enum):
+ """
+ An enumeration for the copy modes supported
+ by numpy.copy() and numpy.array(). The following three modes are supported,
+
+ - ALWAYS: This means that a deep copy of the input
+ array will always be taken.
+ - IF_NEEDED: This means that a deep copy of the input
+ array will be taken only if necessary.
+ - NEVER: This means that the deep copy will never be taken.
+ If a copy cannot be avoided then a `ValueError` will be
+ raised.
+
+ Note that the buffer-protocol could in theory do copies. NumPy currently
+ assumes an object exporting the buffer protocol will never do this.
+ """
+
+ ALWAYS = True
+ IF_NEEDED = False
+ NEVER = 2
+
+ def __bool__(self):
+ # For backwards compatibility
+ if self == _CopyMode.ALWAYS:
+ return True
+
+ if self == _CopyMode.IF_NEEDED:
+ return False
+
+ raise ValueError(f"{self} is neither True nor False.")
+
+
+_CopyMode.__module__ = 'numpy'
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.py
new file mode 100644
index 0000000000000000000000000000000000000000..01ddaaf988347d76d81e7748cd2adb61da77e56e
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.py
@@ -0,0 +1,206 @@
+"""
+Pytest test running.
+
+This module implements the ``test()`` function for NumPy modules. The usual
+boiler plate for doing that is to put the following in the module
+``__init__.py`` file::
+
+ from numpy._pytesttester import PytestTester
+ test = PytestTester(__name__)
+ del PytestTester
+
+
+Warnings filtering and other runtime settings should be dealt with in the
+``pytest.ini`` file in the numpy repo root. The behavior of the test depends on
+whether or not that file is found as follows:
+
+* ``pytest.ini`` is present (develop mode)
+ All warnings except those explicitly filtered out are raised as error.
+* ``pytest.ini`` is absent (release mode)
+ DeprecationWarnings and PendingDeprecationWarnings are ignored, other
+ warnings are passed through.
+
+In practice, tests run from the numpy repo are run in develop mode. That
+includes the standard ``python runtests.py`` invocation.
+
+This module is imported by every numpy subpackage, so lies at the top level to
+simplify circular import issues. For the same reason, it contains no numpy
+imports at module scope, instead importing numpy within function calls.
+"""
+import sys
+import os
+
+__all__ = ['PytestTester']
+
+
+def _show_numpy_info():
+ import numpy as np
+
+ print("NumPy version %s" % np.__version__)
+ relaxed_strides = np.ones((10, 1), order="C").flags.f_contiguous
+ print("NumPy relaxed strides checking option:", relaxed_strides)
+ info = np.lib.utils._opt_info()
+ print("NumPy CPU features: ", (info if info else 'nothing enabled'))
+
+
+class PytestTester:
+ """
+ Pytest test runner.
+
+ A test function is typically added to a package's __init__.py like so::
+
+ from numpy._pytesttester import PytestTester
+ test = PytestTester(__name__).test
+ del PytestTester
+
+ Calling this test function finds and runs all tests associated with the
+ module and all its sub-modules.
+
+ Attributes
+ ----------
+ module_name : str
+ Full path to the package to test.
+
+ Parameters
+ ----------
+ module_name : module name
+ The name of the module to test.
+
+ Notes
+ -----
+ Unlike the previous ``nose``-based implementation, this class is not
+ publicly exposed as it performs some ``numpy``-specific warning
+ suppression.
+
+ """
+ def __init__(self, module_name):
+ self.module_name = module_name
+
+ def __call__(self, label='fast', verbose=1, extra_argv=None,
+ doctests=False, coverage=False, durations=-1, tests=None):
+ """
+ Run tests for module using pytest.
+
+ Parameters
+ ----------
+ label : {'fast', 'full'}, optional
+ Identifies the tests to run. When set to 'fast', tests decorated
+ with `pytest.mark.slow` are skipped, when 'full', the slow marker
+ is ignored.
+ verbose : int, optional
+ Verbosity value for test outputs, in the range 1-3. Default is 1.
+ extra_argv : list, optional
+ List with any extra arguments to pass to pytests.
+ doctests : bool, optional
+ .. note:: Not supported
+ coverage : bool, optional
+ If True, report coverage of NumPy code. Default is False.
+ Requires installation of (pip) pytest-cov.
+ durations : int, optional
+ If < 0, do nothing, If 0, report time of all tests, if > 0,
+ report the time of the slowest `timer` tests. Default is -1.
+ tests : test or list of tests
+ Tests to be executed with pytest '--pyargs'
+
+ Returns
+ -------
+ result : bool
+ Return True on success, false otherwise.
+
+ Notes
+ -----
+ Each NumPy module exposes `test` in its namespace to run all tests for
+ it. For example, to run all tests for numpy.lib:
+
+ >>> np.lib.test() #doctest: +SKIP
+
+ Examples
+ --------
+ >>> result = np.lib.test() #doctest: +SKIP
+ ...
+ 1023 passed, 2 skipped, 6 deselected, 1 xfailed in 10.39 seconds
+ >>> result
+ True
+
+ """
+ import pytest
+ import warnings
+
+ module = sys.modules[self.module_name]
+ module_path = os.path.abspath(module.__path__[0])
+
+ # setup the pytest arguments
+ pytest_args = ["-l"]
+
+ # offset verbosity. The "-q" cancels a "-v".
+ pytest_args += ["-q"]
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("always")
+ # Filter out distutils cpu warnings (could be localized to
+ # distutils tests). ASV has problems with top level import,
+ # so fetch module for suppression here.
+ from numpy.distutils import cpuinfo
+
+ with warnings.catch_warnings(record=True):
+ # Ignore the warning from importing the array_api submodule. This
+ # warning is done on import, so it would break pytest collection,
+ # but importing it early here prevents the warning from being
+ # issued when it imported again.
+ import numpy.array_api
+
+ # Filter out annoying import messages. Want these in both develop and
+ # release mode.
+ pytest_args += [
+ "-W ignore:Not importing directory",
+ "-W ignore:numpy.dtype size changed",
+ "-W ignore:numpy.ufunc size changed",
+ "-W ignore::UserWarning:cpuinfo",
+ ]
+
+ # When testing matrices, ignore their PendingDeprecationWarnings
+ pytest_args += [
+ "-W ignore:the matrix subclass is not",
+ "-W ignore:Importing from numpy.matlib is",
+ ]
+
+ if doctests:
+ pytest_args += ["--doctest-modules"]
+
+ if extra_argv:
+ pytest_args += list(extra_argv)
+
+ if verbose > 1:
+ pytest_args += ["-" + "v"*(verbose - 1)]
+
+ if coverage:
+ pytest_args += ["--cov=" + module_path]
+
+ if label == "fast":
+ # not importing at the top level to avoid circular import of module
+ from numpy.testing import IS_PYPY
+ if IS_PYPY:
+ pytest_args += ["-m", "not slow and not slow_pypy"]
+ else:
+ pytest_args += ["-m", "not slow"]
+
+ elif label != "full":
+ pytest_args += ["-m", label]
+
+ if durations >= 0:
+ pytest_args += ["--durations=%s" % durations]
+
+ if tests is None:
+ tests = [self.module_name]
+
+ pytest_args += ["--pyargs"] + list(tests)
+
+ # run tests.
+ _show_numpy_info()
+
+ try:
+ code = pytest.main(pytest_args)
+ except SystemExit as exc:
+ code = exc.code
+
+ return code == 0
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.pyi b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..67ac87b33de164c710a25110d45545e24a06d42e
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_pytesttester.pyi
@@ -0,0 +1,18 @@
+from collections.abc import Iterable
+from typing import Literal as L
+
+__all__: list[str]
+
+class PytestTester:
+ module_name: str
+ def __init__(self, module_name: str) -> None: ...
+ def __call__(
+ self,
+ label: L["fast", "full"] = ...,
+ verbose: int = ...,
+ extra_argv: None | Iterable[str] = ...,
+ doctests: L[False] = ...,
+ coverage: bool = ...,
+ durations: int = ...,
+ tests: None | Iterable[str] = ...,
+ ) -> bool: ...
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_version.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_version.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a7f017ac411379e5c83a2d10a4ea984c1f2592a
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/_version.py
@@ -0,0 +1,21 @@
+
+# This file was generated by 'versioneer.py' (0.26) from
+# revision-control system data, or from the parent directory name of an
+# unpacked source archive. Distribution tarballs contain a pre-generated copy
+# of this file.
+
+import json
+
+version_json = '''
+{
+ "date": "2023-06-25T20:31:30-0600",
+ "dirty": false,
+ "error": null,
+ "full-revisionid": "9315a9072b2636f75c831b4eca9f42a5f67ca2fb",
+ "version": "1.24.4"
+}
+''' # END VERSION_JSON
+
+
+def get_versions():
+ return json.loads(version_json)
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/conftest.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/conftest.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d110c874884c04822ae7e52d9a67518ed94fa08
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/conftest.py
@@ -0,0 +1,136 @@
+"""
+Pytest configuration and fixtures for the Numpy test suite.
+"""
+import os
+import tempfile
+
+import hypothesis
+import pytest
+import numpy
+
+from numpy.core._multiarray_tests import get_fpu_mode
+
+
+_old_fpu_mode = None
+_collect_results = {}
+
+# Use a known and persistent tmpdir for hypothesis' caches, which
+# can be automatically cleared by the OS or user.
+hypothesis.configuration.set_hypothesis_home_dir(
+ os.path.join(tempfile.gettempdir(), ".hypothesis")
+)
+
+# We register two custom profiles for Numpy - for details see
+# https://hypothesis.readthedocs.io/en/latest/settings.html
+# The first is designed for our own CI runs; the latter also
+# forces determinism and is designed for use via np.test()
+hypothesis.settings.register_profile(
+ name="numpy-profile", deadline=None, print_blob=True,
+)
+hypothesis.settings.register_profile(
+ name="np.test() profile",
+ deadline=None, print_blob=True, database=None, derandomize=True,
+ suppress_health_check=list(hypothesis.HealthCheck),
+)
+# Note that the default profile is chosen based on the presence
+# of pytest.ini, but can be overridden by passing the
+# --hypothesis-profile=NAME argument to pytest.
+_pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini")
+hypothesis.settings.load_profile(
+ "numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile"
+)
+
+
+def pytest_configure(config):
+ config.addinivalue_line("markers",
+ "valgrind_error: Tests that are known to error under valgrind.")
+ config.addinivalue_line("markers",
+ "leaks_references: Tests that are known to leak references.")
+ config.addinivalue_line("markers",
+ "slow: Tests that are very slow.")
+ config.addinivalue_line("markers",
+ "slow_pypy: Tests that are very slow on pypy.")
+
+
+def pytest_addoption(parser):
+ parser.addoption("--available-memory", action="store", default=None,
+ help=("Set amount of memory available for running the "
+ "test suite. This can result to tests requiring "
+ "especially large amounts of memory to be skipped. "
+ "Equivalent to setting environment variable "
+ "NPY_AVAILABLE_MEM. Default: determined"
+ "automatically."))
+
+
+def pytest_sessionstart(session):
+ available_mem = session.config.getoption('available_memory')
+ if available_mem is not None:
+ os.environ['NPY_AVAILABLE_MEM'] = available_mem
+
+
+#FIXME when yield tests are gone.
+@pytest.hookimpl()
+def pytest_itemcollected(item):
+ """
+ Check FPU precision mode was not changed during test collection.
+
+ The clumsy way we do it here is mainly necessary because numpy
+ still uses yield tests, which can execute code at test collection
+ time.
+ """
+ global _old_fpu_mode
+
+ mode = get_fpu_mode()
+
+ if _old_fpu_mode is None:
+ _old_fpu_mode = mode
+ elif mode != _old_fpu_mode:
+ _collect_results[item] = (_old_fpu_mode, mode)
+ _old_fpu_mode = mode
+
+
+@pytest.fixture(scope="function", autouse=True)
+def check_fpu_mode(request):
+ """
+ Check FPU precision mode was not changed during the test.
+ """
+ old_mode = get_fpu_mode()
+ yield
+ new_mode = get_fpu_mode()
+
+ if old_mode != new_mode:
+ raise AssertionError("FPU precision mode changed from {0:#x} to {1:#x}"
+ " during the test".format(old_mode, new_mode))
+
+ collect_result = _collect_results.get(request.node)
+ if collect_result is not None:
+ old_mode, new_mode = collect_result
+ raise AssertionError("FPU precision mode changed from {0:#x} to {1:#x}"
+ " when collecting the test".format(old_mode,
+ new_mode))
+
+
+@pytest.fixture(autouse=True)
+def add_np(doctest_namespace):
+ doctest_namespace['np'] = numpy
+
+@pytest.fixture(autouse=True)
+def env_setup(monkeypatch):
+ monkeypatch.setenv('PYTHONHASHSEED', '0')
+
+
+@pytest.fixture(params=[True, False])
+def weak_promotion(request):
+ """
+ Fixture to ensure "legacy" promotion state or change it to use the new
+ weak promotion (plus warning). `old_promotion` should be used as a
+ parameter in the function.
+ """
+ state = numpy._get_promotion_state()
+ if request.param:
+ numpy._set_promotion_state("weak_and_warn")
+ else:
+ numpy._set_promotion_state("legacy")
+
+ yield request.param
+ numpy._set_promotion_state(state)
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4bafca1bd11448a093ea7758b954541010a305f
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.py
@@ -0,0 +1,547 @@
+"""
+============================
+``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
+from numpy import (
+ integer, ndarray, dtype as _dtype, asarray, frombuffer
+)
+from numpy.core.multiarray import _flagdict, flagsobj
+
+try:
+ import ctypes
+except ImportError:
+ ctypes = None
+
+if ctypes is None:
+ 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_array = _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
+ 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.
+ """
+ if ctypes.__version__ < '1.0.1':
+ import warnings
+ warnings.warn("All features of ctypes interface may not work "
+ "with ctypes < 1.0.1", stacklevel=2)
+
+ # 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:
+ # Try to load library with platform-specific name, otherwise
+ # default to libname.[so|pyd]. Sometimes, these files are built
+ # erroneously on non-linux platforms.
+ from numpy.distutils.misc_util import get_shared_lib_extension
+ so_ext = get_shared_lib_extension()
+ libname_ext = [libname + so_ext]
+ # mac, windows and linux >= py3.2 shared library and loadable
+ # module have different extensions so try both
+ so_ext2 = get_shared_lib_extension(is_python_ext=True)
+ if not so_ext2 == so_ext:
+ libname_ext.insert(0, libname + so_ext2)
+ 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 += _flagdict[val]
+ return num
+
+_flagnames = ['C_CONTIGUOUS', 'F_CONTIGUOUS', 'ALIGNED', 'WRITEABLE',
+ 'OWNDATA', 'WRITEBACKIFCOPY']
+def _flags_fromnum(num):
+ res = []
+ for key in _flagnames:
+ value = _flagdict[key]
+ if (num & value):
+ res.append(key)
+ return res
+
+
+class _ndptr(_ndptr_base):
+ @classmethod
+ def from_param(cls, obj):
+ if not isinstance(obj, ndarray):
+ raise TypeError("argument must be an ndarray")
+ if cls._dtype_ is not None \
+ and obj.dtype != cls._dtype_:
+ raise TypeError("array must have data type %s" % 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("array must have shape %s" % str(cls._shape_))
+ if cls._flags_ is not None \
+ and ((obj.flags.num & cls._flags_) != cls._flags_):
+ raise TypeError("array must have flags %s" %
+ _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 = _dtype((self._dtype_, self._shape_))
+ full_ctype = ctypes.c_char * full_dtype.itemsize
+ buffer = ctypes.cast(self, ctypes.POINTER(full_ctype)).contents
+ return 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 = {}
+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 an Optional[dtype]
+ if dtype is not None:
+ dtype = _dtype(dtype)
+
+ # normalize flags to an Optional[int]
+ num = None
+ if flags is not None:
+ if isinstance(flags, str):
+ flags = flags.split(',')
+ elif isinstance(flags, (int, integer)):
+ num = flags
+ flags = _flags_fromnum(num)
+ elif isinstance(flags, 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 an Optional[tuple]
+ 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("ndpointer_%s"%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 {_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(
+ "Converting {!r} to a ctypes type".format(dtype)
+ ) 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, name, ctype 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,), dict(
+ _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,), dict(
+ _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)
+
+
+ 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
+
+ """
+ return _ctype_from_dtype(_dtype(dtype))
+
+
+ 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
+ """
+ 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 asarray(obj)
+
+
+ def as_ctypes(obj):
+ """Create and return a ctypes object from a numpy array. Actually
+ anything that exposes the __array_interface__ is accepted."""
+ 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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.pyi b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..0313cd82a5a9b900324abc83596c58769b41f56d
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/ctypeslib.pyi
@@ -0,0 +1,251 @@
+# NOTE: Numpy's mypy plugin is used for importing the correct
+# platform-specific `ctypes._SimpleCData[int]` sub-type
+from ctypes import c_int64 as _c_intp
+
+import os
+import sys
+import ctypes
+from collections.abc import Iterable, Sequence
+from typing import (
+ Literal as L,
+ Any,
+ Union,
+ TypeVar,
+ Generic,
+ overload,
+ ClassVar,
+)
+
+from numpy import (
+ ndarray,
+ dtype,
+ generic,
+ bool_,
+ byte,
+ short,
+ intc,
+ int_,
+ longlong,
+ ubyte,
+ ushort,
+ uintc,
+ uint,
+ ulonglong,
+ single,
+ double,
+ longdouble,
+ void,
+)
+from numpy.core._internal import _ctypes
+from numpy.core.multiarray import flagsobj
+from numpy._typing import (
+ # Arrays
+ NDArray,
+ _ArrayLike,
+
+ # Shapes
+ _ShapeLike,
+
+ # DTypes
+ DTypeLike,
+ _DTypeLike,
+ _VoidDTypeLike,
+ _BoolCodes,
+ _UByteCodes,
+ _UShortCodes,
+ _UIntCCodes,
+ _UIntCodes,
+ _ULongLongCodes,
+ _ByteCodes,
+ _ShortCodes,
+ _IntCCodes,
+ _IntCodes,
+ _LongLongCodes,
+ _SingleCodes,
+ _DoubleCodes,
+ _LongDoubleCodes,
+)
+
+# TODO: Add a proper `_Shape` bound once we've got variadic typevars
+_DType = TypeVar("_DType", bound=dtype[Any])
+_DTypeOptional = TypeVar("_DTypeOptional", bound=None | dtype[Any])
+_SCT = TypeVar("_SCT", bound=generic)
+
+_FlagsKind = 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[_DTypeOptional]):
+ # In practice these 4 classvars are defined in the dynamic class
+ # returned by `ndpointer`
+ _dtype_: ClassVar[_DTypeOptional]
+ _shape_: ClassVar[None]
+ _ndim_: ClassVar[None | int]
+ _flags_: ClassVar[None | list[_FlagsKind]]
+
+ @overload
+ @classmethod
+ def from_param(cls: type[_ndptr[None]], obj: ndarray[Any, Any]) -> _ctypes: ...
+ @overload
+ @classmethod
+ def from_param(cls: type[_ndptr[_DType]], obj: ndarray[Any, _DType]) -> _ctypes: ...
+
+class _concrete_ndptr(_ndptr[_DType]):
+ _dtype_: ClassVar[_DType]
+ _shape_: ClassVar[tuple[int, ...]]
+ @property
+ def contents(self) -> ndarray[Any, _DType]: ...
+
+def load_library(
+ libname: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+ loader_path: str | bytes | os.PathLike[str] | os.PathLike[bytes],
+) -> ctypes.CDLL: ...
+
+__all__: list[str]
+
+c_intp = _c_intp
+
+@overload
+def ndpointer(
+ dtype: None = ...,
+ ndim: int = ...,
+ shape: None | _ShapeLike = ...,
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+) -> type[_ndptr[None]]: ...
+@overload
+def ndpointer(
+ dtype: _DTypeLike[_SCT],
+ ndim: int = ...,
+ *,
+ shape: _ShapeLike,
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+) -> type[_concrete_ndptr[dtype[_SCT]]]: ...
+@overload
+def ndpointer(
+ dtype: DTypeLike,
+ ndim: int = ...,
+ *,
+ shape: _ShapeLike,
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+) -> type[_concrete_ndptr[dtype[Any]]]: ...
+@overload
+def ndpointer(
+ dtype: _DTypeLike[_SCT],
+ ndim: int = ...,
+ shape: None = ...,
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+) -> type[_ndptr[dtype[_SCT]]]: ...
+@overload
+def ndpointer(
+ dtype: DTypeLike,
+ ndim: int = ...,
+ shape: None = ...,
+ flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+) -> type[_ndptr[dtype[Any]]]: ...
+
+@overload
+def as_ctypes_type(dtype: _BoolCodes | _DTypeLike[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: _IntCodes | _DTypeLike[int_] | type[int | ctypes.c_long]) -> type[ctypes.c_long]: ...
+@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: _UIntCodes | _DTypeLike[uint] | 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[_SCT], shape: None | _ShapeLike = ...) -> NDArray[_SCT]: ...
+@overload
+def as_array(obj: object, shape: None | _ShapeLike = ...) -> NDArray[Any]: ...
+
+@overload
+def as_ctypes(obj: 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: int_) -> ctypes.c_long: ...
+@overload
+def as_ctypes(obj: longlong) -> ctypes.c_longlong: ...
+@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: uint) -> ctypes.c_ulong: ...
+@overload
+def as_ctypes(obj: ulonglong) -> ctypes.c_ulonglong: ...
+@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[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[int_]) -> ctypes.Array[ctypes.c_long]: ...
+@overload
+def as_ctypes(obj: NDArray[longlong]) -> ctypes.Array[ctypes.c_longlong]: ...
+@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[uint]) -> ctypes.Array[ctypes.c_ulong]: ...
+@overload
+def as_ctypes(obj: NDArray[ulonglong]) -> ctypes.Array[ctypes.c_ulonglong]: ...
+@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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/dual.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/dual.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb7e61aac08581403f09420b5114c779bbf4d71b
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/dual.py
@@ -0,0 +1,83 @@
+"""
+.. deprecated:: 1.20
+
+*This module is deprecated. Instead of importing functions from*
+``numpy.dual``, *the functions should be imported directly from NumPy
+or SciPy*.
+
+Aliases for functions which may be accelerated by SciPy.
+
+SciPy_ can be built to use accelerated or otherwise improved libraries
+for FFTs, linear algebra, and special functions. This module allows
+developers to transparently support these accelerated functions when
+SciPy is available but still support users who have only installed
+NumPy.
+
+.. _SciPy : https://www.scipy.org
+
+"""
+import warnings
+
+
+warnings.warn('The module numpy.dual is deprecated. Instead of using dual, '
+ 'use the functions directly from numpy or scipy.',
+ category=DeprecationWarning,
+ stacklevel=2)
+
+# This module should be used for functions both in numpy and scipy if
+# you want to use the numpy version if available but the scipy version
+# otherwise.
+# Usage --- from numpy.dual import fft, inv
+
+__all__ = ['fft', 'ifft', 'fftn', 'ifftn', 'fft2', 'ifft2',
+ 'norm', 'inv', 'svd', 'solve', 'det', 'eig', 'eigvals',
+ 'eigh', 'eigvalsh', 'lstsq', 'pinv', 'cholesky', 'i0']
+
+import numpy.linalg as linpkg
+import numpy.fft as fftpkg
+from numpy.lib import i0
+import sys
+
+
+fft = fftpkg.fft
+ifft = fftpkg.ifft
+fftn = fftpkg.fftn
+ifftn = fftpkg.ifftn
+fft2 = fftpkg.fft2
+ifft2 = fftpkg.ifft2
+
+norm = linpkg.norm
+inv = linpkg.inv
+svd = linpkg.svd
+solve = linpkg.solve
+det = linpkg.det
+eig = linpkg.eig
+eigvals = linpkg.eigvals
+eigh = linpkg.eigh
+eigvalsh = linpkg.eigvalsh
+lstsq = linpkg.lstsq
+pinv = linpkg.pinv
+cholesky = linpkg.cholesky
+
+_restore_dict = {}
+
+def register_func(name, func):
+ if name not in __all__:
+ raise ValueError("{} not a dual function.".format(name))
+ f = sys._getframe(0).f_globals
+ _restore_dict[name] = f[name]
+ f[name] = func
+
+def restore_func(name):
+ if name not in __all__:
+ raise ValueError("{} not a dual function.".format(name))
+ try:
+ val = _restore_dict[name]
+ except KeyError:
+ return
+ else:
+ sys._getframe(0).f_globals[name] = val
+
+def restore_all():
+ for name in _restore_dict.keys():
+ restore_func(name)
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbe3df27f6ecdb39bc86e77596446f5de26a2f53
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.py
@@ -0,0 +1,186 @@
+#!/usr/bin/env python3
+"""Fortran to Python Interface Generator.
+
+"""
+__all__ = ['run_main', 'compile', 'get_include']
+
+import sys
+import subprocess
+import os
+
+from . import f2py2e
+from . import diagnose
+
+run_main = f2py2e.run_main
+main = f2py2e.main
+
+
+def compile(source,
+ modulename='untitled',
+ extra_args='',
+ verbose=True,
+ source_fn=None,
+ extension='.f',
+ full_output=False
+ ):
+ """
+ Build extension module from a Fortran 77 source string with f2py.
+
+ Parameters
+ ----------
+ source : str or bytes
+ Fortran source of module / subroutine to compile
+
+ .. versionchanged:: 1.16.0
+ Accept str as well as bytes
+
+ modulename : str, optional
+ The name of the compiled python module
+ extra_args : str or list, optional
+ Additional parameters passed to f2py
+
+ .. versionchanged:: 1.16.0
+ A list of args may also be provided.
+
+ verbose : bool, optional
+ Print f2py output to screen
+ source_fn : str, optional
+ Name of the file where the fortran source is written.
+ The default is to use a temporary file with the extension
+ provided by the ``extension`` parameter
+ extension : ``{'.f', '.f90'}``, optional
+ Filename extension if `source_fn` is not provided.
+ The extension tells which fortran standard is used.
+ The default is ``.f``, which implies F77 standard.
+
+ .. versionadded:: 1.11.0
+
+ full_output : bool, optional
+ If True, return a `subprocess.CompletedProcess` containing
+ the stdout and stderr of the compile process, instead of just
+ the status code.
+
+ .. versionadded:: 1.20.0
+
+
+ Returns
+ -------
+ result : int or `subprocess.CompletedProcess`
+ 0 on success, or a `subprocess.CompletedProcess` if
+ ``full_output=True``
+
+ Examples
+ --------
+ .. literalinclude:: ../../source/f2py/code/results/compile_session.dat
+ :language: python
+
+ """
+ import tempfile
+ import shlex
+
+ if source_fn is None:
+ f, fname = tempfile.mkstemp(suffix=extension)
+ # f is a file descriptor so need to close it
+ # carefully -- not with .close() directly
+ os.close(f)
+ else:
+ fname = source_fn
+
+ if not isinstance(source, str):
+ source = str(source, 'utf-8')
+ try:
+ with open(fname, 'w') as f:
+ f.write(source)
+
+ args = ['-c', '-m', modulename, f.name]
+
+ if isinstance(extra_args, str):
+ is_posix = (os.name == 'posix')
+ extra_args = shlex.split(extra_args, posix=is_posix)
+
+ args.extend(extra_args)
+
+ c = [sys.executable,
+ '-c',
+ 'import numpy.f2py as f2py2e;f2py2e.main()'] + args
+ try:
+ cp = subprocess.run(c, capture_output=True)
+ except OSError:
+ # preserve historic status code used by exec_command()
+ cp = subprocess.CompletedProcess(c, 127, stdout=b'', stderr=b'')
+ else:
+ if verbose:
+ print(cp.stdout.decode())
+ finally:
+ if source_fn is None:
+ os.remove(fname)
+
+ if full_output:
+ return cp
+ else:
+ return cp.returncode
+
+
+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)
+ ``_fblas-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("module {!r} has no attribute "
+ "{!r}".format(__name__, attr))
+
+
+def __dir__():
+ return list(globals().keys() | {"test"})
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.pyi b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..6e3a82cf8f444166e9cda92db637565c30db11c3
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__init__.pyi
@@ -0,0 +1,43 @@
+import os
+import subprocess
+from collections.abc import Iterable
+from typing import Literal as L, Any, overload, TypedDict
+
+from numpy._pytesttester import PytestTester
+
+class _F2PyDictBase(TypedDict):
+ csrc: list[str]
+ h: list[str]
+
+class _F2PyDict(_F2PyDictBase, total=False):
+ fsrc: list[str]
+ ltx: list[str]
+
+__all__: list[str]
+__path__: list[str]
+test: PytestTester
+
+def run_main(comline_list: Iterable[str]) -> dict[str, _F2PyDict]: ...
+
+@overload
+def compile( # type: ignore[misc]
+ source: str | bytes,
+ modulename: str = ...,
+ extra_args: str | list[str] = ...,
+ verbose: bool = ...,
+ source_fn: None | str | bytes | os.PathLike[Any] = ...,
+ extension: L[".f", ".f90"] = ...,
+ full_output: L[False] = ...,
+) -> int: ...
+@overload
+def compile(
+ source: str | bytes,
+ modulename: str = ...,
+ extra_args: str | list[str] = ...,
+ verbose: bool = ...,
+ source_fn: None | str | bytes | os.PathLike[Any] = ...,
+ extension: L[".f", ".f90"] = ...,
+ full_output: L[True] = ...,
+) -> subprocess.CompletedProcess[bytes]: ...
+
+def get_include() -> str: ...
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__main__.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__main__.py
new file mode 100644
index 0000000000000000000000000000000000000000..936a753a2796896667aa782277be41b40af061d3
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__version__.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__version__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e20d7c1dbb38807d248ff886e30425e7ff597299
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/__version__.py
@@ -0,0 +1 @@
+from numpy.version import version
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/auxfuncs.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/auxfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f9b0ceafa216e98ccc62ec54ac258229da74f1a
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/auxfuncs.py
@@ -0,0 +1,890 @@
+#!/usr/bin/env python3
+"""
+
+Auxiliary functions for f2py2e.
+
+Copyright 1999,2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/07/24 19:01:55 $
+Pearu Peterson
+
+"""
+import pprint
+import sys
+import types
+from functools import reduce
+
+from . import __version__
+from . import cfuncs
+
+__all__ = [
+ 'applyrules', 'debugcapi', 'dictappend', 'errmess', 'gentitle',
+ 'getargs2', 'getcallprotoargument', 'getcallstatement',
+ 'getfortranname', 'getpymethoddef', 'getrestdoc', 'getusercode',
+ 'getusercode1', 'hasbody', 'hascallstatement', 'hascommon',
+ 'hasexternals', 'hasinitvalue', 'hasnote', 'hasresultnote',
+ 'isallocatable', 'isarray', 'isarrayofstrings',
+ 'ischaracter', 'ischaracterarray', 'ischaracter_or_characterarray',
+ 'iscomplex',
+ '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', 'isrequired',
+ 'isroutine', 'isscalar', 'issigned_long_longarray', 'isstring',
+ 'isstringarray', 'isstring_or_stringarray', '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', 'show', 'stripcomma', 'throw_error', 'isattr_value'
+]
+
+
+f2py_version = __version__.version
+
+
+errmess = sys.stderr.write
+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 isrequired(var):
+ return not isoptional(var) and isintent_nothide(var)
+
+
+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 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 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 = '\n\n var = %s\n Message: %s\n' % (var, self.mess)
+ 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('%s:%s' % (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('%s:%s' % (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('Failed to use fortranname from %s\n' %
+ (rout['f2pyenhancements']))
+ 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("%s multiline block should end with `'''`: %s\n"
+ % (blockname, repr(r)))
+ 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
+ else:
+ if 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 '/*%s %s %s*/' % (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('#%s#' % (k), sep.join(flatlist(d[k])))
+ else:
+ str = str.replace('#%s#' % (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)
+ if 'supertext' in res:
+ i = res['supertext']
+ else:
+ i = ''
+ ret[k].append(replace(i, d))
+ else:
+ i = rules[k][k1]
+ if isinstance(i, dict):
+ res = applyrules({'supertext': i}, d)
+ if 'supertext' in res:
+ i = res['supertext']
+ else:
+ i = ''
+ ret[k].append(replace(i, d))
+ else:
+ errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))
+ if isinstance(ret[k], list):
+ if len(ret[k]) == 1:
+ ret[k] = ret[k][0]
+ if ret[k] == []:
+ del ret[k]
+ return ret
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/capi_maps.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/capi_maps.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaae3a8e0b1556054ac37f7fa7839d472d13b465
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/capi_maps.py
@@ -0,0 +1,880 @@
+#!/usr/bin/env python3
+"""
+
+Copyright 1999,2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/05/06 10:57:33 $
+Pearu Peterson
+
+"""
+from . import __version__
+f2py_version = __version__.version
+
+import copy
+import re
+import os
+from .crackfortran import markoutercomma
+from . import cb_rules
+
+# 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 *
+
+__all__ = [
+ 'getctype', 'getstrlength', 'getarrdims', 'getpydocsign',
+ 'getarrdocsign', 'getinit', 'sign2map', 'routsign2map', 'modsign2map',
+ 'cb_sign2map', 'cb_routsign2map', 'common_sign2map'
+]
+
+
+# Numarray and Numeric users should set this False
+using_newcore = True
+
+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_DOUBLE', # forced casting
+ 'char': 'NPY_STRING',
+ 'unsigned_char': 'NPY_UBYTE',
+ 'signed_char': 'NPY_BYTE',
+ 'short': 'NPY_SHORT',
+ 'unsigned_short': 'NPY_USHORT',
+ 'int': 'NPY_INT',
+ 'unsigned': 'NPY_UINT',
+ 'long': 'NPY_LONG',
+ 'long_long': 'NPY_LONG', # forced casting
+ 'complex_float': 'NPY_CFLOAT',
+ 'complex_double': 'NPY_CDOUBLE',
+ 'complex_long_double': 'NPY_CDOUBLE', # forced casting
+ 'string': 'NPY_STRING',
+ 'character': 'NPY_CHAR'}
+
+# These new maps aren't used anywhere yet, but should be by default
+# unless building numeric or numarray extensions.
+if using_newcore:
+ 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': 'd', # forced casting
+ 'char': '1',
+ 'signed_char': '1',
+ 'unsigned_char': 'b',
+ 'short': 's',
+ 'unsigned_short': 'w',
+ 'int': 'i',
+ 'unsigned': 'u',
+ 'long': 'l',
+ 'long_long': 'L',
+ 'complex_float': 'F',
+ 'complex_double': 'D',
+ 'complex_long_double': 'D', # forced casting
+ 'string': 'c',
+ 'character': 'c'
+ }
+
+if using_newcore:
+ 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 is NumPy agnostic, so no need to bother with using_newcore
+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'},
+ }
+
+f2cmap_default = copy.deepcopy(f2cmap_all)
+
+f2cmap_mapped = []
+
+def load_f2cmap_file(f2cmap_file):
+ global f2cmap_all
+
+ 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('Reading f2cmap from {!r} ...\n'.format(f2cmap_file))
+ with open(f2cmap_file, 'r') as f:
+ d = eval(f.read().lower(), {}, {})
+ for k, d1 in d.items():
+ for k1 in d1.keys():
+ d1[k1.lower()] = d1[k1]
+ d[k.lower()] = d[k]
+ for k in d.keys():
+ if k not in f2cmap_all:
+ f2cmap_all[k] = {}
+ for k1 in d[k].keys():
+ if d[k][k1] in c2py_map:
+ if k1 in f2cmap_all[k]:
+ outmess(
+ "\tWarning: redefinition of {'%s':{'%s':'%s'->'%s'}}\n" % (k, k1, f2cmap_all[k][k1], d[k][k1]))
+ f2cmap_all[k][k1] = d[k][k1]
+ outmess('\tMapping "%s(kind=%s)" to "%s"\n' %
+ (k, k1, d[k][k1]))
+ f2cmap_mapped.append(d[k][k1])
+ else:
+ errmess("\tIgnoring map {'%s':{'%s':'%s'}}: '%s' must be in %s\n" % (
+ k, k1, d[k][k1], d[k][k1], list(c2py_map.keys())))
+ outmess('Successfully applied user defined f2cmap changes\n')
+ except Exception as msg:
+ errmess(
+ 'Failed to apply user defined f2cmap changes: %s. Skipping.\n' % (msg))
+
+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('getctype: function %s has no return value?!\n' % a)
+ 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()))
+ else:
+ if not isexternal(var):
+ errmess('getctype: No C-type found in "%s", assuming void.\n' % var)
+ 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('getstrlength: function %s has no return value?!\n' % a)
+ if not isstring(var):
+ errmess(
+ 'getstrlength: expected a signature of a string but got: %s\n' % (repr(var)))
+ 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(
+ 'getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d)))
+ 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('getctype: function %s has no return value?!\n' % af)
+ 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 = ', optional\\n Default: %s' % 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 = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init)
+ sigout = '%s : %s' % (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 = '%s : %s string(len=%s)%s' % (
+ a, opt, getstrlength(var), init)
+ sigout = '%s : string(len=%s)' % (out_a, 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 = ' => %s' % ua
+ else:
+ ua = ''
+ sig = '%s : call-back function%s' % (a, ua)
+ sigout = sig
+ else:
+ errmess(
+ 'getpydocsign: Could not resolve docsignature for "%s".\n' % a)
+ return sig, sigout
+
+
+def getarrdocsign(a, var):
+ ctype = getctype(var)
+ if isstring(var) and (not isarray(var)):
+ sig = '%s : rank-0 array(string(len=%s),\'c\')' % (a,
+ getstrlength(var))
+ elif isscalar(var):
+ sig = '%s : rank-0 array(%s,\'%s\')' % (a, 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(
+ 'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a))
+ if isarray(var):
+ init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (
+ ret['init.r'], ret['init.i'])
+ elif isstring(var):
+ if not init:
+ init, showinit = '""', "''"
+ if init[0] == "'":
+ init = '"%s"' % (init[1:-1].replace('"', '\\"'))
+ if init[0] == '"':
+ showinit = "'%s'" % (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('F2PY_%s' % 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('slen(%s)=%s' % (a, ret['length']))
+ if isarray(var):
+ ddim = ','.join(
+ map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim))
+ rl.append('dims(%s)' % ddim)
+ if isexternal(var):
+ ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (
+ 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'] = 'debug-capi:%s=%s' % (
+ a, cformat_map[ret['ctype']])
+ if isstring(var):
+ ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
+ a, a)
+ if isexternal(var):
+ ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a)
+ if ret['ctype'] in cformat_map:
+ ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']])
+ ret['showvalueformat'] = '%s' % (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('end of %s' % 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 'externals' in rout and rout['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 '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'] = '%s' % (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': 'cb_%s_in_%s' % (rout['name'], um),
+ 'returncptr': ''}
+ if isintent_callback(rout):
+ if '_' in rout['name']:
+ F_FUNC = 'F_FUNC_US'
+ else:
+ F_FUNC = 'F_FUNC'
+ ret['callbackname'] = '%s(%s,%s)' \
+ % (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('end of %s' % 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'] = '%s' % (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
+"""
+ else:
+ if 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): # obsolute
+ 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'] = '%s' % (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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cb_rules.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cb_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..761831e004492aa97b1841ff6d0163665c5791ac
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cb_rules.py
@@ -0,0 +1,649 @@
+#!/usr/bin/env python3
+"""
+
+Build call-back mechanism for f2py2e.
+
+Copyright 2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/07/20 11:27:58 $
+Pearu Peterson
+
+"""
+from . import __version__
+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
+)
+from . import cfuncs
+
+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(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('warning: empty body for %s\n' % (m['name']))
+
+
+def buildcallback(rout, um):
+ from . import capi_maps
+
+ outmess(' Constructing call-back function "cb_%s_in_%s"\n' %
+ (rout['name'], um))
+ 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(' %s\n' % (ar['docstrshort']))
+ return
+################## Build call-back function #############
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cfuncs.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..7416925624eea10d0880f60861a4f4906cb89106
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/cfuncs.py
@@ -0,0 +1,1522 @@
+#!/usr/bin/env python3
+"""
+
+C declarations, CPP macros, and C functions for f2py2e.
+Only required declarations/macros/functions will be used.
+
+Copyright 1999,2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/05/06 11:42:34 $
+Pearu Peterson
+
+"""
+import sys
+import copy
+
+from . import __version__
+
+f2py_version = __version__.version
+errmess = sys.stderr.write
+
+##################### 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['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'] = '#define pyobj_from_char1(v) (PyLong_FromLong(v))'
+cppmacros[
+ 'pyobj_from_short1'] = '#define pyobj_from_short1(v) (PyLong_FromLong(v))'
+needs['pyobj_from_int1'] = ['signed_char']
+cppmacros['pyobj_from_int1'] = '#define pyobj_from_int1(v) (PyLong_FromLong(v))'
+cppmacros[
+ 'pyobj_from_long1'] = '#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
+"""
+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) \\
+ && !defined(__STDC_NO_THREADS__) \\
+ && (!defined(__GLIBC__) || __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ > 12)) \\
+ && !defined(NPY_OS_OPENBSD) && !defined(NPY_OS_HAIKU)
+/* __STDC_NO_THREADS__ was first defined in a maintenance release of glibc 2.12,
+ see https://lists.gnu.org/archive/html/commit-hurd/2012-07/msg00180.html,
+ so `!defined(__STDC_NO_THREADS__)` may give false positive for the existence
+ of `threads.h` when using an older release of glibc 2.12
+ See gh-19437 for details on OpenBSD */
+#include
+#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'] = """\
+static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache;
+static int initforcomb(npy_intp *dims,int nd,int tr) {
+ int k;
+ if (dims==NULL) return 0;
+ if (nd<0) return 0;
+ forcombcache.nd = nd;
+ forcombcache.d = dims;
+ forcombcache.tr = tr;
+ if ((forcombcache.i = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
+ if ((forcombcache.i_tr = (int *)malloc(sizeof(int)*nd))==NULL) return 0;
+ for (k=1;k 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);
+ }
+ }
+ {
+ char mess[F2PY_MESSAGE_BUFFER_SIZE];
+ strcpy(mess, errmess);
+ PyObject* err = PyErr_Occurred();
+ if (err == NULL) {
+ err = PyExc_TypeError;
+ }
+ sprintf(mess + strlen(mess),
+ " -- expected str|bytes|sequence-of-str-or-bytes, got ");
+ f2py_describe(obj, mess + strlen(mess));
+ PyErr_SetString(err, mess);
+ }
+ return 0;
+}
+"""
+
+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) && PyArray_TYPE(obj) == NPY_LONGDOUBLE) {
+ (*v) = *((npy_longdouble *)PyArray_DATA(obj));
+ 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']
+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) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) {
+ (*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real;
+ (*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag;
+ 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']
+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)new.real;
+ (*v).i = (double)new.imag;
+ }
+ else if (PyArray_IsScalar(obj, CLongDouble)) {
+ npy_clongdouble new;
+ PyArray_ScalarAsCtype(obj, &new);
+ (*v).r = (double)new.real;
+ (*v).i = (double)new.imag;
+ }
+ 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_cdouble *)PyArray_DATA(arr))->real;
+ (*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag;
+ 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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/common_rules.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/common_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a488bf5a5a4170da91c49ec75afba5f0376d579
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/common_rules.py
@@ -0,0 +1,149 @@
+#!/usr/bin/env python3
+"""
+
+Build common block mechanism for f2py2e.
+
+Copyright 2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/05/06 10:57:33 $
+Pearu Peterson
+
+"""
+from . import __version__
+f2py_version = __version__.version
+
+from .auxfuncs import (
+ hasbody, hascommon, hasnote, isintent_hide, outmess
+)
+from . import capi_maps
+from . import func2subr
+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] = '%s\n %s' % (s[0], line)
+ chooks = ['']
+
+ def cadd(line, s=chooks):
+ s[0] = '%s\n%s' % (s[0], line)
+ ihooks = ['']
+
+ def iadd(line, s=ihooks):
+ s[0] = '%s\n%s' % (s[0], line)
+ doc = ['']
+
+ def dadd(line, s=doc):
+ s[0] = '%s\n%s' % (s[0], 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('subroutine f2pyinit%s(setupfunc)' % name)
+ fadd('external setupfunc')
+ for n in vnames:
+ fadd(func2subr.var2fixfortran(vars, n))
+ if name == '_BLNK_':
+ fadd('common %s' % (','.join(vnames)))
+ else:
+ fadd('common /%s/ %s' % (name, ','.join(vnames)))
+ fadd('call setupfunc(%s)' % (','.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('(%s)' % (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('\tf2py_%s_def[i_f2py++].data = %s;' % (name, 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('\ttmp = PyFortranObject_New(f2py_%s_def,f2py_init_%s);' % (name, name))
+ iadd('\tif (tmp == NULL) return NULL;')
+ iadd('\tif (F2PyDict_SetItemString(d, \"%s\", tmp) == -1) return NULL;'
+ % name)
+ 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('--- %s' % (note))
+ dadd('\\end{description}')
+ ret['docs'].append(
+ '"\t/%s/ %s\\n"' % (name, ','.join(map(lambda v, d: v + d, inames, idims))))
+ ret['commonhooks'] = chooks
+ ret['initcommonhooks'] = ihooks
+ ret['latexdoc'] = doc[0]
+ if len(ret['docs']) <= 1:
+ ret['docs'] = ''
+ return ret, fwrap[0]
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/crackfortran.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/crackfortran.py
new file mode 100644
index 0000000000000000000000000000000000000000..63597cef15739014317a708ab80c6d918636def7
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/crackfortran.py
@@ -0,0 +1,3545 @@
+#!/usr/bin/env python3
+"""
+crackfortran --- read fortran (77,90) code and extract declaration information.
+
+Copyright 1999-2004 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/09/27 07:13:49 $
+Pearu Peterson
+
+
+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 sys
+import string
+import fileinput
+import re
+import os
+import copy
+import platform
+import codecs
+try:
+ import charset_normalizer
+except ImportError:
+ charset_normalizer = None
+
+from . import __version__
+
+# 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 . import symbolic
+
+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('rmbadname1: Replacing "%s" with "%s".\n' %
+ (name, badnames[name]))
+ return badnames[name]
+ return name
+
+
+def rmbadname(names):
+ return [rmbadname1(_m) for _m in names]
+
+
+def undo_rmbadname1(name):
+ if name in invbadnames:
+ errmess('undo_rmbadname1: Replacing "%s" with "%s".\n'
+ % (name, invbadnames[name]))
+ return invbadnames[name]
+ return name
+
+
+def undo_rmbadname(names):
+ return [undo_rmbadname1(_m) for _m in names]
+
+
+def getextension(name):
+ i = name.rfind('.')
+ if i == -1:
+ return ''
+ if '\\' in name[i:]:
+ return ''
+ if '/' in name[i:]:
+ return ''
+ return name[i + 1:]
+
+is_f_file = re.compile(r'.*\.(for|ftn|f77|f)\Z', re.I).match
+_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
+
+
+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(file):
+ """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 = 0
+ with openhook(file, 'r') as f:
+ line = f.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 = 1
+ 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 = 1
+ break
+ line = f.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 is_f_file(currentfilename) 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]
+ if not strictf77:
+ (l, rl) = split_by_unquoted(l, '!')
+ l += ' '
+ if rl[:5].lower() == '!f2py': # f2py directive
+ l, _ = split_by_unquoted(l + 4 * ' ' + rl[5:], '!')
+ 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:]
+ else: # Skip comment line
+ cont = False
+ continue
+ elif strictf77:
+ if len(l) > 72:
+ l = l[:72]
+ if not (l[0] 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:
+ if not strictf77:
+ # F90 continuation
+ 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:]
+ if localdolowercase:
+ finalline = ll.lower()
+ else:
+ finalline = ll
+ origfinalline = ll
+ ll = l
+ cont = (r is not None)
+ else:
+ # clean up line beginning from possible digits.
+ l = ' ' + l[5:]
+ 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:
+ finalline = ll.lower()
+ else:
+ finalline = ll
+ origfinalline = ll
+ ll = l
+ cont = (r is not None)
+ else:
+ raise ValueError(
+ "Flag sourcecodeform must be either 'fix' or 'free': %s" % 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
+ 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, r'.*'), re.I), 'end'
+endifs = r'end\s*(if|do|where|select|while|forall|associate|block|' + \
+ r'critical|enum|team)'
+endifpattern = re.compile(
+ beforethisafter % (r'[\w]*?', endifs, endifs, r'[\w\s]*'), re.I), 'endif'
+#
+moduleprocedures = r'module\s*procedure'
+moduleprocedurepattern = re.compile(
+ beforethisafter % ('', moduleprocedures, moduleprocedures, r'.*'), 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="[^\"'{}]".format(re.escape(characters)),
+ char="[{}]".format(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)
+
+
+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 = 'callfun %s(%s) result (%s)' % (
+ name, a, m2.group('result'))
+ else:
+ line = 'callfun %s(%s)' % (name, a)
+ m = callfunpattern[0].match(line)
+ if not m:
+ outmess(
+ 'crackline: could not resolve function call for line=%s.\n' % repr(line))
+ 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('appenddecl: "%s" not implemented.\n' % k)
+ 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 _resolvenameargspattern(line):
+ line = markouterparen(line)
+ m1 = nameargspattern.match(line)
+ if m1:
+ return m1.group('name'), m1.group('args'), m1.group('result'), m1.group('bind')
+ 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):
+ 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(
+ 'analyzeline: no group yet. Creating program group with name "%s".\n' % newname)
+ 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] = dict(attrspec = attrs)
+ args = []
+ result = None
+ else:
+ name, args, result, _ = _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
+ else:
+ if 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
+ 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, bind = _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 == 'operator' or k == '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(
+ 'analyzeline: intent(callback) %s is ignored\n' % (k))
+ 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(
+ 'analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n' % (e, ll))
+ 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'):
+ if 'implicit' in groupcache[groupcounter]:
+ impl = groupcache[groupcounter]['implicit']
+ else:
+ impl = {}
+ 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(
+ 'analyzeline: could not extract info of implicit statement part "%s"\n' % (e))
+ continue
+ m2 = typespattern4implicit.match(m1.group('this'))
+ if not m2:
+ outmess(
+ 'analyzeline: could not extract types pattern of implicit statement part "%s"\n' % (e))
+ 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(
+ 'analyzeline: expected "-" instead of "%s" in range list of implicit statement\n' % r)
+ continue
+ else:
+ begc = endc = r.strip()
+ if not len(begc) == len(endc) == 1:
+ outmess(
+ 'analyzeline: expected "-" instead of "%s" in range list of implicit statement (2)\n' % r)
+ 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 = {}
+ if 'vars' in groupcache[groupcounter]:
+ vars = groupcache[groupcounter]['vars']
+ last_name = None
+ for l in ll:
+ l = [x.strip() for x in l]
+ if l[0][0] == ',':
+ l[0] = l[0][1:]
+ if l[0][0] == '(':
+ outmess(
+ 'analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0])
+ continue
+ i = 0
+ j = 0
+ llen = len(l[1])
+ for v in rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')]):
+ if v[0] == '(':
+ outmess(
+ 'analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % v)
+ # XXX: subsequent init expressions may get wrong values.
+ # Ignoring since data statements are irrelevant for
+ # wrapping.
+ continue
+ fc = 0
+ while (i < llen) and (fc or not l[1][i] == ','):
+ if l[1][i] == "'":
+ fc = not fc
+ i = i + 1
+ i = i + 1
+ if v not in vars:
+ vars[v] = {}
+ if '=' in vars[v] and not vars[v]['='] == l[1][j:i - 1]:
+ outmess('analyzeline: changing init expression of "%s" ("%s") to "%s"\n' % (
+ v, vars[v]['='], l[1][j:i - 1]))
+ vars[v]['='] = l[1][j:i - 1]
+ j = i
+ last_name = v
+ groupcache[groupcounter]['vars'] = vars
+ if last_name is not None:
+ previous_context = ('variable', last_name, groupcounter)
+ elif case == 'common':
+ line = m.group('after').strip()
+ if not line[0] == '/':
+ line = '//' + line
+ cl = []
+ f = 0
+ bn = ''
+ ol = ''
+ for c in line:
+ if c == '/':
+ f = f + 1
+ continue
+ if f >= 3:
+ bn = bn.strip()
+ if not bn:
+ bn = '_BLNK_'
+ cl.append([bn, ol])
+ f = f - 2
+ bn = ''
+ ol = ''
+ if f % 2:
+ bn = bn + c
+ else:
+ ol = ol + c
+ 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(
+ 'analyzeline: Not local=>use pattern found in %s\n' % repr(l))
+ else:
+ rl[l] = l
+ groupcache[groupcounter]['use'][name]['map'] = rl
+ else:
+ pass
+ 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'))
+ else:
+ if 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)
+ return
+
+
+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):
+ global groupcache, groupcounter
+
+ last_name = None
+ kindselect, charselect, typename = cracktypespec(typespec, selector)
+ 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(
+ 'updatevars: no name pattern found for entity=%s. Skipping.\n' % (repr(e)))
+ 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:
+ 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 'len' in d1 and 'array' in d1:
+ if d1['len'] == '':
+ d1['len'] = d1['array']
+ del d1['array']
+ 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 'array' in d1:
+ dm = 'dimension(%s)' % 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(
+ 'cracktypespec: no kindselector pattern found for %s\n' % (repr(selector)))
+ 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(
+ 'cracktypespec: no charselector pattern found for %s\n' % (repr(selector)))
+ 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('cracktypespec: no selector used for %s\n' %
+ (repr(selector)))
+ 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 = 'In: %s:%s\n' % (block['from'], block['name'])
+ 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('get_useparameters: mapping for %s not impl.\n' % (mapping))
+ 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('%sBlock: %s\n' % (tab, block['name']), 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('%sBlock: %s\n' % (tab, block['name']), 0)
+ block = analyzeargs(block)
+ block = analyzecommon(block)
+ block['vars'] = analyzevars(block)
+ block['sortvars'] = sortvarnames(block['vars'])
+ if 'args' in block and block['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 'externals' in block and block['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 '%s_%i' % (mname, i) in userisdefined:
+ i = i + 1
+ mname = '%s_%i' % (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)
+ else:
+ if 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(
+ 'dimension(%s)' % (','.join(dims)))
+ else:
+ block['vars'][n]['attrspec'] = [
+ 'dimension(%s)' % (','.join(dims))]
+ else:
+ if dims:
+ block['vars'][n] = {
+ 'attrspec': ['dimension(%s)' % (','.join(dims))]}
+ else:
+ block['vars'][n] = {}
+ if n not in commonvars:
+ commonvars.append(n)
+ else:
+ n = e
+ errmess(
+ 'analyzecommon: failed to extract "[()]" from "%s" in common /%s/.\n' % (e, k))
+ 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)
+ 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']
+ 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(
+ 'buildimplicitrules: no implicit rules for routine %s.\n' % repr(block['name']))
+ 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('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 = '%s(%s)%s' % (
+ m1.group('before'), 0, m1.group('after'))
+ m1 = re_1.match(ee)
+ b = myeval(ee, {}, {})
+ m1 = re_1.match(e)
+ while m1:
+ ee = '%s(%s)%s' % (
+ m1.group('before'), 1, m1.group('after'))
+ m1 = re_1.match(ee)
+ a = myeval(ee, {}, {}) - b
+ m1 = re_1.match(e)
+ while m1:
+ ee = '%s(%s)%s' % (
+ 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 = '%s(%s)%s' % (
+ 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('_get_depend_dict: no dependence info for %s\n' % (repr(name)))
+ 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 good for 0 <= p <= 20
+ if p < 7:
+ return 4
+ if p < 16:
+ return 8
+ machine = platform.machine().lower()
+ if machine.startswith(('aarch64', 'power', 'ppc', 'riscv', 's390x', 'sparc')):
+ if p <= 20:
+ return 16
+ else:
+ if p < 19:
+ return 10
+ elif p <= 20:
+ 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]:
+ 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')
+
+ # Handle _dp for gh-6624
+ # Also fixes gh-20460
+ if real16pattern.search(v):
+ v = 8
+ elif real8pattern.search(v):
+ v = 4
+ try:
+ params[n] = eval(v, g_params, params)
+
+ except Exception as msg:
+ params[n] = v
+ outmess('get_parameters: got "%s" on %s\n' % (msg, repr(v)))
+ 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(
+ 'get_parameters:parameter %s does not have value?!\n' % (repr(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):
+ 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) | set(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))
+
+ 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('@,@')]):
+ star = ':' if d == ':' else '*'
+ # Evaluate `d` with respect to params
+ if d in params:
+ d = str(params[d])
+ 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)
+
+ if d == star:
+ dl = [star]
+ 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] != star:
+ 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 = set(
+ 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
+ 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(
+ 'analyzevars: prefix (%s) were not used\n' % repr(block['prefix']))
+ if not block['block'] 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 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']:
+ if orig_a in block['vars']:
+ block['vars'][a] = block['vars'][orig_a]
+ else:
+ block['vars'][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(
+ 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
+ return {'typespec': 'integer'}
+ m = determineexprtype_re_3.match(expr)
+ if m:
+ if 'name' in m.groupdict() and m.group('name'):
+ outmess(
+ 'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
+ 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(
+ 'determineexprtype: could not determine expressions (%s) type.\n' % (repr(expr)))
+ 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 = '(%s)' % ','.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 = ' result (%s)' % 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 = '! in %s' % block['from']
+ if 'entry' in block:
+ entry_stmts = ''
+ for k, i in list(block['entry'].items()):
+ entry_stmts = '%s%sentry %s(%s)' \
+ % (entry_stmts, tab + tabchar, 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 = '%s%scommon %s' % (ret, tab, ','.join(common[k]))
+ else:
+ ret = '%s%scommon /%s/ %s' % (ret, tab, k, ','.join(common[k]))
+ return ret
+
+
+def use2fortran(use, tab=''):
+ ret = ''
+ for m in list(use.keys()):
+ ret = '%s%suse %s,' % (ret, tab, m)
+ if use[m] == {}:
+ if ret and ret[-1] == ',':
+ ret = ret[:-1]
+ continue
+ if 'only' in use[m] and use[m]['only']:
+ ret = '%s only:' % (ret)
+ 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 = '%s%s%s' % (ret, c, k)
+ c = ','
+ else:
+ ret = '%s%s%s=>%s' % (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()['isintent_%s' % intent]
+ except KeyError:
+ pass
+ else:
+ if f(var):
+ ret.append(intent)
+ return ret
+
+
+def vars2fortran(block, vars, args, tab='', as_interface=False):
+ """
+ TODO:
+ public sub
+ ...
+ """
+ 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(
+ 'vars2fortran: Confused?!: "%s" is not defined in vars.\n' % a)
+ 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(
+ 'vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n' % (a, d))
+ if 'externals' in block and a in block['externals']:
+ if isintent_callback(vars[a]):
+ ret = '%s%sintent(callback) %s' % (ret, tab, a)
+ ret = '%s%sexternal %s' % (ret, tab, a)
+ if isoptional(vars[a]):
+ ret = '%s%soptional %s' % (ret, tab, 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('vars2fortran: No definition for argument "%s".\n' % a)
+ 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 = '%s%sexternal %s' % (ret, tab, a)
+ continue
+ show(vars[a])
+ outmess('vars2fortran: No typespec for argument "%s".\n' % a)
+ continue
+ vardef = vars[a]['typespec']
+ if vardef == 'type' and 'typename' in vars[a]:
+ vardef = '%s(%s)' % (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 = '%s*(%s)' % (vardef, selector['*'])
+ else:
+ vardef = '%s*%s' % (vardef, selector['*'])
+ else:
+ if 'len' in selector:
+ vardef = '%s(len=%s' % (vardef, selector['len'])
+ if 'kind' in selector:
+ vardef = '%s,kind=%s)' % (vardef, selector['kind'])
+ else:
+ vardef = '%s)' % (vardef)
+ elif 'kind' in selector:
+ vardef = '%s(kind=%s)' % (vardef, 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 = '%s, %s' % (vardef, ','.join(attr))
+ c = ','
+ if 'dimension' in vars[a]:
+ vardef = '%s%sdimension(%s)' % (
+ vardef, c, ','.join(vars[a]['dimension']))
+ c = ','
+ if 'intent' in vars[a]:
+ lst = true_intent_list(vars[a])
+ if lst:
+ vardef = '%s%sintent(%s)' % (vardef, c, ','.join(lst))
+ c = ','
+ if 'check' in vars[a]:
+ vardef = '%s%scheck(%s)' % (vardef, c, ','.join(vars[a]['check']))
+ c = ','
+ if 'depend' in vars[a]:
+ vardef = '%s%sdepend(%s)' % (
+ vardef, c, ','.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 = '(%s,%s)' % (v.real, v.imag)
+ except Exception:
+ pass
+ vardef = '%s :: %s=%s' % (vardef, a, v)
+ else:
+ vardef = '%s :: %s' % (vardef, a)
+ ret = '%s%s%s' % (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=parents + [parent],
+ result=result, *args, **kwargs)
+ if new_index is not None:
+ new_result.append(new_item)
+ elif isinstance(obj, dict):
+ new_result = dict()
+ for key, value in obj.items():
+ new_key, new_value = traverse((key, value), visit,
+ parents=parents + [parent],
+ result=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('Unknown option %s\n' % repr(l))
+ 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('Writing fortran code to file %s\n' % repr(pyffilename), 0)
+ pyf = crack2fortran(postlist)
+ with open(pyffilename, 'w') as f:
+ f.write(pyf)
+ if showblocklist:
+ show(postlist)
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/diagnose.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/diagnose.py
new file mode 100644
index 0000000000000000000000000000000000000000..21ee399f035f3042134c162511659e50c2a90e93
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/diagnose.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+import os
+import sys
+import tempfile
+
+
+def run_command(cmd):
+ print('Running %r:' % (cmd))
+ os.system(cmd)
+ print('------')
+
+
+def run():
+ _path = os.getcwd()
+ os.chdir(tempfile.gettempdir())
+ print('------')
+ print('os.name=%r' % (os.name))
+ print('------')
+ print('sys.platform=%r' % (sys.platform))
+ print('------')
+ print('sys.version:')
+ print(sys.version)
+ print('------')
+ print('sys.prefix:')
+ print(sys.prefix)
+ print('------')
+ print('sys.path=%r' % (':'.join(sys.path)))
+ print('------')
+
+ try:
+ import numpy
+ has_newnumpy = 1
+ except ImportError:
+ print('Failed to import new numpy:', sys.exc_info()[1])
+ has_newnumpy = 0
+
+ try:
+ from numpy.f2py import f2py2e
+ has_f2py2e = 1
+ except ImportError:
+ print('Failed to import f2py2e:', sys.exc_info()[1])
+ has_f2py2e = 0
+
+ try:
+ import numpy.distutils
+ has_numpy_distutils = 2
+ except ImportError:
+ try:
+ import numpy_distutils
+ has_numpy_distutils = 1
+ except ImportError:
+ print('Failed to import numpy_distutils:', sys.exc_info()[1])
+ has_numpy_distutils = 0
+
+ if has_newnumpy:
+ try:
+ print('Found new numpy version %r in %s' %
+ (numpy.__version__, 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 obsolute 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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f2py2e.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f2py2e.py
new file mode 100644
index 0000000000000000000000000000000000000000..10508488dc0432d62fa7720d3b2b3d8c5d2f24f1
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f2py2e.py
@@ -0,0 +1,704 @@
+#!/usr/bin/env python3
+"""
+
+f2py2e - Fortran to Python C/API generator. 2nd Edition.
+ See __usage__ below.
+
+Copyright 1999--2011 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/05/06 08:31:19 $
+Pearu Peterson
+
+"""
+import sys
+import os
+import pprint
+import re
+from pathlib import Path
+
+from . import crackfortran
+from . import rules
+from . import cb_rules
+from . import auxfuncs
+from . import cfuncs
+from . import f90mod_rules
+from . import __version__
+from . import capi_maps
+
+f2py_version = __version__.version
+numpy_version = __version__.version
+errmess = sys.stderr.write
+# outmess=sys.stdout.write
+show = pprint.pprint
+outmess = auxfuncs.outmess
+
+__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:
+
+ --2d-numpy Use numpy.f2py tool with NumPy support. [DEFAULT]
+ --2d-numeric Use f2py2e tool with Numeric support.
+ --2d-numarray Use f2py2e tool with Numarray support.
+ --g3-numpy Use 3rd generation f2py from the separate f2py package.
+ [NOT AVAILABLE YET]
+
+ -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.
+
+ --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.
+
+
+numpy.distutils options (only effective with -c):
+
+ --fcompiler= Specify Fortran compiler type by vendor
+ --compiler= Specify C compiler type (as defined by distutils)
+
+ --help-fcompiler List available Fortran compilers and exit
+ --f77exec= Specify the path to F77 compiler
+ --f90exec= Specify the path to F90 compiler
+ --f77flags= Specify F77 compiler flags
+ --f90flags= Specify F90 compiler flags
+ --opt= Specify optimization flags
+ --arch= Specify architecture specific optimization flags
+ --noopt Compile without optimization
+ --noarch Compile without arch-dependent optimization
+ --debug Compile with debugging information
+
+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.
+
+ -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
+ -DUNDERSCORE_G77
+
+ 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}
+Requires: Python 3.5 or higher.
+License: NumPy license (see LICENSE.txt in the NumPy source code)
+Copyright 1999 - 2011 Pearu Peterson all rights reserved.
+https://web.archive.org/web/20140822061353/http://cens.ioc.ee/projects/f2py2e"""
+
+
+def scaninputline(inputline):
+ files, skipfuncs, onlyfuncs, debug = [], [], [], []
+ f, f2, f3, f5, f6, f7, f8, f9, f10 = 1, 0, 0, 0, 0, 0, 0, 0, 0
+ verbose = 1
+ emptygen = True
+ dolc = -1
+ dolatexdoc = 0
+ dorestdoc = 0
+ wrapfuncs = 1
+ buildpath = '.'
+ include_paths = []
+ 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[:15] in '--include_paths':
+ outmess(
+ 'f2py option --include_paths is deprecated, use --include-paths instead.\n')
+ f7 = 1
+ elif l[:15] in '--include-paths':
+ f7 = 1
+ elif l == '--skip-empty-wrappers':
+ emptygen = False
+ elif l[0] == '-':
+ errmess('Unknown option %s\n' % repr(l))
+ sys.exit()
+ elif f2:
+ f2 = 0
+ signsfile = l
+ elif f3:
+ f3 = 0
+ modulename = l
+ elif f6:
+ f6 = 0
+ buildpath = l
+ elif f7:
+ f7 = 0
+ include_paths.extend(l.split(os.pathsep))
+ 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('Creating build directory %s\n' % (buildpath))
+ 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(
+ 'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))
+ 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.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('Saving signatures to file "%s"\n' % (options['signsfile']))
+ 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"] = "%smodule.c" % mod["name"]
+ else:
+ for mod in postlist:
+ mod["coutput"] = options["coutput"]
+ if options["f2py_wrapper_output"] is None:
+ for mod in postlist:
+ mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]
+ else:
+ for mod in postlist:
+ mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
+ 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')
+ 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:
+ if plist['block'] == 'python module' and '__user__' in plist['name']:
+ if plist['name'] in isusedby:
+ # if not quiet:
+ outmess(
+ f'Skipping Makefile build for module "{plist["name"]}" '
+ 'which is used by {}\n'.format(
+ ','.join(f'"{s}"' for s in isusedby[plist['name']])))
+ if 'signsfile' in options:
+ if options['verbose'] > 1:
+ outmess(
+ 'Stopping. Edit the signature file and then run f2py on the signature file: ')
+ outmess('%s %s\n' %
+ (os.path.basename(sys.argv[0]), options['signsfile']))
+ 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
+
+
+def run_compile():
+ """
+ Do it all in one call!
+ """
+ import tempfile
+
+ 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)|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]
+ _reg4 = re.compile(
+ r'--((f(77|90)(flags|exec)|opt|arch)=|(debug|noopt|noarch|help-fcompiler))')
+ fc_flags = [_m for _m in sys.argv[1:] if _reg4.match(_m)]
+ sys.argv = [_m for _m in sys.argv if _m not in fc_flags]
+
+ del_list = []
+ for s in flib_flags:
+ v = '--fcompiler='
+ if s[:len(v)] == v:
+ 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('Unknown vendor: "%s"' % (s[len(v):]))
+ nv = ov
+ i = flib_flags.index(s)
+ flib_flags[i] = '--fcompiler=' + nv
+ 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')
+
+ modulename = 'untitled'
+ sources = sys.argv[1:]
+
+ for optname in ['--include_paths', '--include-paths', '--f2cmap']:
+ if optname in sys.argv:
+ i = sys.argv.index(optname)
+ f2py_flags.extend(sys.argv[i:i + 2])
+ del sys.argv[i + 1], sys.argv[i]
+ sources = sys.argv[1:]
+
+ if '-m' in sys.argv:
+ i = sys.argv.index('-m')
+ modulename = sys.argv[i + 1]
+ del sys.argv[i + 1], sys.argv[i]
+ sources = sys.argv[1:]
+ else:
+ from numpy.distutils.command.build_src import get_f2py_modulename
+ pyf_files, sources = filter_files('', '[.]pyf([.]src|)', sources)
+ sources = pyf_files + sources
+ for f in pyf_files:
+ modulename = get_f2py_modulename(f)
+ if modulename:
+ break
+
+ extra_objects, sources = filter_files('', '[.](o|a|so|dylib)', sources)
+ include_dirs, sources = filter_files('-I', '', sources, remove_prefix=1)
+ 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)
+
+ from numpy.distutils.system_info import get_info
+
+ num_info = {}
+ if num_info:
+ include_dirs.extend(num_info.get('include_dirs', []))
+
+ from numpy.distutils.core import setup, Extension
+ ext_args = {'name': modulename, 'sources': sources,
+ 'include_dirs': include_dirs,
+ 'library_dirs': library_dirs,
+ 'libraries': libraries,
+ 'define_macros': define_macros,
+ 'undef_macros': undef_macros,
+ 'extra_objects': extra_objects,
+ 'f2py_options': f2py_flags,
+ }
+
+ if sysinfo_flags:
+ from numpy.distutils.misc_util import dict_append
+ for n in sysinfo_flags:
+ i = get_info(n)
+ if not i:
+ outmess('No %s resources found in system'
+ ' (try `f2py --help-link`)\n' % (repr(n)))
+ dict_append(ext_args, **i)
+
+ ext = Extension(**ext_args)
+ sys.argv = [sys.argv[0]] + setup_flags
+ sys.argv.extend(['build',
+ '--build-temp', build_dir,
+ '--build-base', build_dir,
+ '--build-platlib', '.',
+ # disable CCompilerOpt
+ '--disable-optimization'])
+ if fc_flags:
+ sys.argv.extend(['config_fc'] + fc_flags)
+ if flib_flags:
+ sys.argv.extend(['build_ext'] + flib_flags)
+
+ setup(ext_modules=[ext])
+
+ if remove_build_dir and os.path.exists(build_dir):
+ import shutil
+ outmess('Removing build directory %s\n' % (build_dir))
+ shutil.rmtree(build_dir)
+
+
+def main():
+ if '--help-link' in sys.argv[1:]:
+ sys.argv.remove('--help-link')
+ from numpy.distutils.system_info import show_all
+ show_all()
+ return
+
+ # Probably outdated options that were not working before 1.16
+ if '--g3-numpy' in sys.argv[1:]:
+ sys.stderr.write("G3 f2py support is not implemented, yet.\\n")
+ sys.exit(1)
+ elif '--2e-numeric' in sys.argv[1:]:
+ sys.argv.remove('--2e-numeric')
+ elif '--2e-numarray' in sys.argv[1:]:
+ # Note that this errors becaust the -DNUMARRAY argument is
+ # not recognized. Just here for back compatibility and the
+ # error message.
+ sys.argv.append("-DNUMARRAY")
+ sys.argv.remove('--2e-numarray')
+ elif '--2e-numpy' in sys.argv[1:]:
+ sys.argv.remove('--2e-numpy')
+ else:
+ pass
+
+ if '-c' in sys.argv[1:]:
+ run_compile()
+ else:
+ run_main(sys.argv[1:])
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f90mod_rules.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f90mod_rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3bb6a212a651f354e17b21faa40a81882860309
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/f90mod_rules.py
@@ -0,0 +1,264 @@
+#!/usr/bin/env python3
+"""
+
+Build F90 module support for f2py2e.
+
+Copyright 2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/02/03 19:30:23 $
+Pearu Peterson
+
+"""
+__version__ = "$Revision: 1.27 $"[10:-1]
+
+f2py_version = 'See `f2py -v`'
+
+import numpy as np
+
+from . import capi_maps
+from . import func2subr
+from .crackfortran import undo_rmbadname, undo_rmbadname1
+
+# 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 *
+
+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] = '%s\n %s' % (s[0], line)
+ doc = ['']
+
+ def dadd(line, s=doc):
+ s[0] = '%s\n%s' % (s[0], line)
+ 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 (not l_or(isintent_hide, isprivate)(var)):
+ onlyvars.append(n)
+ mfargs.append(n)
+ outmess('\t\tConstructing F90 module support for "%s"...\n' %
+ (m['name']))
+ if onlyvars:
+ outmess('\t\t Variables: %s\n' % (' '.join(onlyvars)))
+ chooks = ['']
+
+ def cadd(line, s=chooks):
+ s[0] = '%s\n%s' % (s[0], line)
+ ihooks = ['']
+
+ def iadd(line, s=ihooks):
+ s[0] = '%s\n%s' % (s[0], 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('--- %s' % (note))
+ if isallocatable(var):
+ fargs.append('f2py_%s_getdims_%s' % (m['name'], n))
+ efargs.append(fargs[-1])
+ sargs.append(
+ 'void (*%s)(int*,int*,void(*)(char*,int*),int*)' % (n))
+ sargsp.append('void (*)(int*,int*,void(*)(char*,int*),int*)')
+ iadd('\tf2py_%s_def[i_f2py++].func = %s;' % (m['name'], n))
+ fadd('subroutine %s(r,s,f2pysetdata,flag)' % (fargs[-1]))
+ fadd('use %s, only: d => %s\n' %
+ (m['name'], undo_rmbadname1(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('end subroutine %s' % (fargs[-1]))
+ else:
+ fargs.append(n)
+ sargs.append('char *%s' % (n))
+ sargsp.append('char*')
+ iadd('\tf2py_%s_def[i_f2py++].data = %s;' % (m['name'], 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('%s()' % (b['name']))
+ b['modulename'] = m['name']
+ api, wrap = rules.buildapi(b)
+ if isfunction(b):
+ fhooks[0] = fhooks[0] + wrap
+ fargs.append('f2pywrap_%s_%s' % (m['name'], b['name']))
+ ifargs.append(func2subr.createfuncwrapper(b, signature=1))
+ else:
+ if wrap:
+ fhooks[0] = fhooks[0] + wrap
+ fargs.append('f2pywrap_%s_%s' % (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('char *%s' % (b['name']))
+ sargsp.append('char *')
+ iadd('\tf2py_%s_def[i_f2py++].data = %s;' %
+ (m['name'], 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('subroutine f2pyinit%s(f2pysetupfunc)' % (m['name']))
+ if mfargs:
+ for a in undo_rmbadname(mfargs):
+ fadd('use %s, only : %s' % (m['name'], a))
+ if ifargs:
+ fadd(' '.join(['interface'] + ifargs))
+ fadd('end interface')
+ fadd('external f2pysetupfunc')
+ if efargs:
+ for a in undo_rmbadname(efargs):
+ fadd('external %s' % (a))
+ fadd('call f2pysetupfunc(%s)' % (','.join(undo_rmbadname(fargs))))
+ fadd('end subroutine f2pyinit%s\n' % (m['name']))
+
+ dadd('\n'.join(ret['latexdoc']).replace(
+ r'\subsection{', r'\subsubsection{'))
+
+ ret['latexdoc'] = []
+ ret['docs'].append('"\t%s --- %s"' % (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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/func2subr.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/func2subr.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a05f065b625de65e4ed7a82ff1a715e9404832d
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/func2subr.py
@@ -0,0 +1,303 @@
+#!/usr/bin/env python3
+"""
+
+Rules for building C/API module with f2py2e.
+
+Copyright 1999,2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2004/11/26 11:13:06 $
+Pearu Peterson
+
+"""
+import copy
+
+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('var2fixfortran: No definition for argument "%s".\n' % a)
+ return ''
+ if 'typespec' not in vars[a]:
+ show(vars[a])
+ outmess('var2fixfortran: No typespec for argument "%s".\n' % a)
+ return ''
+ vardef = vars[a]['typespec']
+ if vardef == 'type' and 'typename' in vars[a]:
+ vardef = '%s(%s)' % (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 = '%s(len=*)' % (vardef)
+ else:
+ vardef = '%s(%s=%s)' % (vardef, lk, selector['*'])
+ else:
+ if selector['*'] in ['*', ':']:
+ vardef = '%s*(%s)' % (vardef, selector['*'])
+ else:
+ vardef = '%s*%s' % (vardef, selector['*'])
+ else:
+ if 'len' in selector:
+ vardef = '%s(len=%s' % (vardef, selector['len'])
+ if 'kind' in selector:
+ vardef = '%s,kind=%s)' % (vardef, selector['kind'])
+ else:
+ vardef = '%s)' % (vardef)
+ elif 'kind' in selector:
+ vardef = '%s(kind=%s)' % (vardef, selector['kind'])
+
+ vardef = '%s %s' % (vardef, fa)
+ if 'dimension' in vars[a]:
+ vardef = '%s(%s)' % (vardef, ','.join(vars[a]['dimension']))
+ return vardef
+
+
+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 = 'f2py_%s_d%s' % (a, i)
+ dv = dict(typespec='integer', intent=['hide'])
+ dv['='] = 'shape(%s, %s)' % (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] = '%s\n %s' % (ret[0], line)
+ name = rout['name']
+ fortranname = getfortranname(rout)
+ f90mode = ismoduleroutine(rout)
+ newname = '%sf2pywrap' % (name)
+
+ 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
+
+ sargs = ', '.join(args)
+ if f90mode:
+ add('subroutine f2pywrap_%s_%s (%s)' %
+ (rout['modulename'], name, sargs))
+ if not signature:
+ add('use %s, only : %s' % (rout['modulename'], fortranname))
+ else:
+ add('subroutine f2pywrap%s (%s)' % (name, sargs))
+ if not need_interface:
+ add('external %s' % (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('external %s' % (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('%s = .not.(.not.%s(%s))' % (newname, fortranname, sargs))
+ else:
+ add('%s = %s(%s)' % (newname, fortranname, sargs))
+ if f90mode:
+ add('end subroutine f2pywrap_%s_%s' % (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 = 'f2py_%s_d%s' % (a, i)
+ dv = dict(typespec='integer', intent=['hide'])
+ dv['='] = 'shape(%s, %s)' % (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] = '%s\n %s' % (ret[0], line)
+ name = rout['name']
+ fortranname = getfortranname(rout)
+ f90mode = ismoduleroutine(rout)
+
+ args = rout['args']
+
+ sargs = ', '.join(args)
+ if f90mode:
+ add('subroutine f2pywrap_%s_%s (%s)' %
+ (rout['modulename'], name, sargs))
+ if not signature:
+ add('use %s, only : %s' % (rout['modulename'], fortranname))
+ else:
+ add('subroutine f2pywrap%s (%s)' % (name, sargs))
+ if not need_interface:
+ add('external %s' % (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('external %s' % (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('call %s(%s)' % (fortranname, sargs))
+ if f90mode:
+ add('end subroutine f2pywrap_%s_%s' % (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('out=%s' % (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/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/rules.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/rules.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bac871024d8e2c646b67467af4add19560b38d3
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/rules.py
@@ -0,0 +1,1571 @@
+#!/usr/bin/env python3
+"""
+
+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,2000 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Date: 2005/08/30 08:58:42 $
+Pearu Peterson
+
+"""
+import os, sys
+import time
+import copy
+from pathlib import Path
+
+# __version__.version is now the same as the NumPy version
+from . import __version__
+
+from .auxfuncs import (
+ applyrules, debugcapi, dictappend, errmess, gentitle, getargs2,
+ hascallstatement, hasexternals, hasinitvalue, hasnote,
+ hasresultnote, isarray, isarrayofstrings, ischaracter,
+ ischaracterarray, ischaracter_or_characterarray, 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, isattr_value,
+ 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, stripcomma, requiresf90wrapper
+)
+
+from . import capi_maps
+from . import cfuncs
+from . import common_rules
+from . import use_rules
+from . import f90mod_rules
+from . import func2subr
+
+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 F2PY_REPORT_ATEXIT
+ if (! PyErr_Occurred())
+ on_exit(f2py_report_on_exit,(void*)\"#modulename#\");
+#endif
+ 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_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': 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\");
+ if (initforcomb(PyArray_DIMS(capi_#varname#_as_array),
+ PyArray_NDIM(capi_#varname#_as_array),1)) {
+ while ((_i = nextforcomb()))
+ #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(' Building module "%s"...\n' % (m['name']))
+ 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(
+ 'buildmodule: Could not find the body of interfaced routine "%s". Skipping.\n' % (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('buildmodule: unknown need %s.\n' % (repr(k)))
+ 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(' Wrote C/API module "%s" to file "%s"\n' % (m['name'], fn))
+
+ 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(
+ '%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version))
+ 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(
+ 'C This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
+ 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(' Fortran 77 wrappers are saved to "%s"\n' % (wn))
+ if funcwrappers2:
+ wn = os.path.join(
+ options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename']))
+ ret['fsrc'] = wn
+ with open(wn, 'w') as f:
+ f.write('! -*- f90 -*-\n')
+ f.write(
+ '! This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
+ 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(' Fortran 90 wrappers are saved to "%s"\n' % (wn))
+ 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(' Constructing wrapper function "%s"...\n' % (rout['name']))
+ # 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(' %s\n' % (ar['docshort']))
+ else:
+ outmess(' %s\n' % (ar['docshort']))
+ return ar, wrap
+
+
+#################### EOF rules.py #######################
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/setup.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..499609f96600ff5ba4dc3573a8f02effaf1adaa8
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/setup.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python3
+"""
+setup.py for installing F2PY
+
+Usage:
+ pip install .
+
+Copyright 2001-2005 Pearu Peterson all rights reserved,
+Pearu Peterson
+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.
+$Revision: 1.32 $
+$Date: 2005/01/30 17:22:14 $
+Pearu Peterson
+
+"""
+from numpy.distutils.core import setup
+from numpy.distutils.misc_util import Configuration
+
+
+from __version__ import version
+
+
+def configuration(parent_package='', top_path=None):
+ config = Configuration('f2py', parent_package, top_path)
+ config.add_subpackage('tests')
+ config.add_data_dir('tests/src')
+ config.add_data_files(
+ 'src/fortranobject.c',
+ 'src/fortranobject.h')
+ config.add_data_files('*.pyi')
+ return config
+
+
+if __name__ == "__main__":
+
+ config = configuration(top_path='')
+ config = config.todict()
+
+ config['classifiers'] = [
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'Intended Audience :: Science/Research',
+ 'License :: OSI Approved :: NumPy License',
+ 'Natural Language :: English',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: C',
+ 'Programming Language :: Fortran',
+ 'Programming Language :: Python',
+ 'Topic :: Scientific/Engineering',
+ 'Topic :: Software Development :: Code Generators',
+ ]
+ setup(version=version,
+ description="F2PY - Fortran to Python Interface Generator",
+ author="Pearu Peterson",
+ author_email="pearu@cens.ioc.ee",
+ maintainer="Pearu Peterson",
+ maintainer_email="pearu@cens.ioc.ee",
+ license="BSD",
+ platforms="Unix, Windows (mingw|cygwin), Mac OSX",
+ long_description="""\
+The Fortran to Python Interface Generator, or F2PY for short, is a
+command line tool (f2py) for generating Python C/API modules for
+wrapping Fortran 77/90/95 subroutines, accessing common blocks from
+Python, and calling Python functions from Fortran (call-backs).
+Interfacing subroutines/data from Fortran 90/95 modules is supported.""",
+ url="https://numpy.org/doc/stable/f2py/",
+ keywords=['Fortran', 'f2py'],
+ **config)
diff --git a/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/symbolic.py b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/symbolic.py
new file mode 100644
index 0000000000000000000000000000000000000000..c2ab0f14000f9a328d270a71f32c6ed6e5929c6d
--- /dev/null
+++ b/VQA_model/DOVER/.eggs/numpy-1.24.4-py3.8-linux-x86_64.egg/numpy/f2py/symbolic.py
@@ -0,0 +1,1510 @@
+"""Fortran/C symbolic expressions
+
+References:
+- J3/21-007: Draft Fortran 202x. https://j3-fortran.org/doc/year/21/21-007.pdf
+"""
+
+# 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 a op-data pair.
+
+ Expr instances are hashable and sortable.
+ """
+
+ @staticmethod
+ def parse(s, language=Language.C):
+ """Parse a Fortran expression to a 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 {